简体   繁体   English

如何将数组的键添加到 php 中的数组值?

[英]how to add the key of an array to the array value in php ?

Hi I have an array and I have added the an id to the key of each array but I want that id to be added to the array value also.嗨,我有一个数组,我已经将一个 id 添加到每个数组的键中,但我希望将该 id 也添加到数组值中。

The code which adds the keys and value to the array.将键和值添加到数组的代码。

foreach ($data as $id => $name) {
            $arr[$id] = Category::where('parent_category_id', $id)->lists('id');
        }

now the array looks like this现在数组看起来像这样

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
                )

        )

what I really want to achieve is that I want to add the key for example say the first key which is 427 to the array values so that I get all the ids.我真正想要实现的是我想添加键,例如说第一个键是 427 到数组值,以便我获得所有的 id。 How would I be able to achieve this please assist.我将如何能够实现这一点,请提供帮助。

I have done this by using following code:我使用以下代码完成了此操作:

$result = [];
array_walk($arr,function($v,$k)use (&$result){
    array_unshift($v,$k);
    $result[$k][] = $v;
});

print_r($result);

You can check working demo here您可以在此处查看工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM