php数组转多维

$arr = [
    [
        'name'     => "项目1",
        'model'    => "金",
        'location' => '苏州',

    ],
    [
        'name'     => "项目1",
        'model'    => "银",
        'location' => '上海',
    ],
    [
        'name'     => "项目2",
        'model'    => "铜",
        'location' => '北京',
    ],
    [
        'name'     => "项目2",
        'model'    => "铜",
        'location' => '深圳',
    ],
];

将上面的一维数组转成多维数组,大致实现以下结构
image.png

$arr = [
    [
        'name'     => "项目1",
        'child'=>[
            [
                'model'    => "金",
                'child'=>[
                    [
                       'location' => '苏州', 
                    ],

                ]
            ],
            [
                'model'    => "银",
                'child'=>[
                    [
                        'location' => '上海',
                    ]
                ]
            ]
        ]
    ],
    [
        'name'     => "项目2",
        'child'=>[
            [
                'model'    => "铜",
                'child'=>[
                    [
                        'location' => '北京',
                    ],
                    [
                        'location' => '深圳',
                    ],
                ]
            ]
        ]
    ],
];

用以下代码,键会是中文,怎么改成键是数值

foreach ($arr as $v) {
      $result[$v['name']][$v['model']][$v['location']][] = $v;
 }
var_dump($result);
阅读 1.7k
1 个回答

来一个比较绕的解法吧,这玩意儿也只好循环了,第一步先扁平化分组是很重要的。

<?php

$arr = [
    [
        'name'     => "项目1",
        'model'    => "金",
        'location' => '苏州',

    ],
    [
        'name'     => "项目1",
        'model'    => "银",
        'location' => '上海',
    ],
    [
        'name'     => "项目2",
        'model'    => "铜",
        'location' => '北京',
    ],
    [
        'name'     => "项目2",
        'model'    => "铜",
        'location' => '深圳',
    ],
];


$result = array_map(function ($name, array $nameChild) {
    return [
        'name'  => $name,
        'child' => array_map(function ($model, array $modelChild) {
            return [
                'model' => $model,
                'child' => array_map(function ($location) {
                    return compact('location');
                }, array_keys($modelChild)),
            ];
        }, array_keys($nameChild), $nameChild),
    ];
}, array_keys($temp1 = array_reduce($arr, function ($result, $current) {
    $result[$current['name']][$current['model']][$current['location']][] = $current;
    return $result;
}, [])), $temp1);

print_r($result);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题