我正在使用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)
我得到了我想要的结果,但最后的结果和以前一样。谢谢!
答案 0 :(得分: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"
}
]
}
}
]
以便您看到结果已更改
答案 1 :(得分:0)