[英]how to add the key of an array to the array value in php ?
嗨,我有一個數組,我已經將一個 id 添加到每個數組的鍵中,但我希望將該 id 也添加到數組值中。
將鍵和值添加到數組的代碼。
foreach ($data as $id => $name) {
$arr[$id] = Category::where('parent_category_id', $id)->lists('id');
}
現在數組看起來像這樣
Array
(
[427] => Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => 277
[1] => 279
[2] => 426
[3] => 428
[4] => 429
[5] => 430
[6] => 431
[7] => 432
[8] => 433
[9] => 434
)
)
[280] => Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => 281
[1] => 282
[2] => 435
[3] => 436
[4] => 437
)
)
[283] => Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => 284
[1] => 285
[2] => 286
)
)
我真正想要實現的是我想添加鍵,例如說第一個鍵是 427 到數組值,以便我獲得所有的 id。 我將如何能夠實現這一點,請提供幫助。
我使用以下代碼完成了此操作:
$result = [];
array_walk($arr,function($v,$k)use (&$result){
array_unshift($v,$k);
$result[$k][] = $v;
});
print_r($result);
您可以在此處查看工作演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.