【问题标题】:how to add the key of an array to the array value in php ?如何将数组的键添加到php中的数组值?
【发布时间】:2016-07-22 05:34:22
【问题描述】:

您好,我有一个数组,我已将一个 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。请协助我如何实现这一目标。

【问题讨论】:

    标签: php arrays collections laravel-5.1


    【解决方案1】:

    我使用以下代码完成了这项工作:

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

    您可以查看工作演示here

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 2012-03-24
      • 1970-01-01
      相关资源
      最近更新 更多