【问题标题】:Array is returned as an object using resource数组使用资源作为对象返回
【发布时间】:2020-08-10 21:52:12
【问题描述】:

发生了一些奇怪的事情。

我有一个这样的数组:

=> [
     "optionalinformation" => [
       "domain" => [
         "type" => "string",
       ],
     ],
   ]

这个数组被一个资源使用,如果我使用 tinker 来检查这个资源,像这样:

$result = App\Http\Resources\ProductResource::make(Product::find(2));

is_array($result->optionalinformation);

在这种情况下,结果是true:这是一个数组。

但是如果 axios 获取结果,我会得到这个:

"optionalinformation": {
      "domain": {
        "type": "string"
      },

它不再是一个数组而是一个对象。任何想法为什么会发生这种情况?

这是我的 api 资源:

 /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'                      => $this->id,
            'title'                   => $this->title,
            'optionalinformation'     => $this->optionalinformation,
        ];
    }

【问题讨论】:

  • 你期待什么样的结果?
  • 好吧:我希望有一个数组。
  • 请贴出js的例子。

标签: laravel vue.js axios laravel-7 laravel-resource


【解决方案1】:

它在定义中。 Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.查看Resource docs

如果您期望返回一个数组,那么我建议您跳过资源并使用->toArray() 直接从控制器传递数据。但是你又在你的 vuejs 中使用了axios,那么我强烈建议你坚持使用json 格式作为预期的响应。

【讨论】:

    【解决方案2】:

    这里有点混乱,主要是由 PHP 术语引起的。

    在 PHP 术语中,关联数组仍然是一个数组。但是关联数组实际上是一个字典。

    其他编程语言不会将关联数组(字典)视为数组,因此具有不同的词汇表。

    您的数据结构实际上是一个字典,而不是数字索引数组。

    从 JSON 的角度来看,如果您的数据结构具有非数字键,那么它会被转换为对象。

    您的困惑源于这样一个事实:is_array 如果变量是从零开始的索引数组,则返回 true,而事实上它对于关联数组也返回 true。

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 2014-11-28
      • 2012-05-30
      • 2020-08-01
      相关资源
      最近更新 更多