2

我正在使用 laravel 并制作了小 api。我有问题keyBy()。我得到这样的回应

"translate": [
    0: {"id": 0, "lang": "az" },
    1: {"id": 0, "lang": "ru" },
    2: {"id": 0, "lang": "en" }
]

我想像这样更改这些数组的键:

"translate": [
    "az": {"id": 0, "lang": "az" },
    "en": {"id": 0, "lang": "ru" },
    "ru": {"id": 0, "lang": "en" }
]

用那个片段

foreach ($categories as $key => $row) {
    if ($row) {
        $row->translate = $row->translate->keyBy('lang');
    }
}

但结果是一样的。数组键不会改变。我不知道为什么。我只是dd($row->translate)得到了我想要的结果,但最后的结果和以前一样。谢谢!

4

2 回答 2

0

translate里面dd($data)

在此处输入图像描述

translate内部json对象(api响应)

在此处输入图像描述

我不知道什么改变了键。

于 2017-12-19T12:31:24.513 回答
0

它应该可以正常工作,我相信问题出在其他地方。看看这个例子:

$object = new stdClass();

$object->translate = collect([
    0 => (object) ['id' => 0, 'lang' => 'az'],
    1 => (object) ['id' => 0, 'lang' => 'ru'],
    2 => (object) ['id' => 0, 'lang' => 'en'],
]);

$object2 = new stdClass();

$object2->translate = collect([
    0 => (object) ['id' => 0, 'lang' => 'x'],
    1 => (object) ['id' => 0, 'lang' => 'y'],
    2 => (object) ['id' => 0, 'lang' => 'z'],
]);

$categories = [$object, $object2];    

foreach ($categories as $key => $row) {
    if ($row){
        $row->translate = $row->translate->keyBy('lang');
    }
}    

dd($categories);

结果有:

array:2 [▼
  0 => {#329 ▼
    +"translate": Collection {#346 ▼
      #items: array:3 [▼
        "az" => {#335 ▼
          +"id": 0
          +"lang": "az"
        }
        "ru" => {#337 ▼
          +"id": 0
          +"lang": "ru"
        }
        "en" => {#338 ▼
          +"id": 0
          +"lang": "en"
        }
      ]
    }
  }
  1 => {#340 ▼
    +"translate": Collection {#345 ▼
      #items: array:3 [▼
        "x" => {#341 ▼
          +"id": 0
          +"lang": "x"
        }
        "y" => {#342 ▼
          +"id": 0
          +"lang": "y"
        }
        "z" => {#343 ▼
          +"id": 0
          +"lang": "z"
        }
      ]
    }
  }
]

如您所见,结果已更改

于 2017-12-18T11:20:03.907 回答