如何分组和回显多维数组

时间:2019-05-20 13:54:56

标签: php arrays multidimensional-array

我想从我的数据库中回显多维数组,我试图在stackoverflow中进行搜索,但是我不能很好地实现。

这是我的数组:

Array (
    [0] => Array (
            [product_name] => BMW
            [category_name] => Car
        )
    [1] => Array(
            [product_name] => Jaguar
            [category_name] => Car
        )
    [2] => Array(
            [product_name] => Toyota
            [category_name] => Car
        )
    [3] => Array (
            [product_name] => Jeep
            [category_name] => Car
        )
    [4] => Array (
            [product_name] => Ducati
            [category_name] => Bike
        )

)

我需要将此数组分组为:

Array(
    [0] => Array(
            [category_name] => Car
            [product_name] => Array(
                    [0] => Array(
                            [product_name] => BMW
                        )

                    [1] => Array(
                            [product_name] => Toyota
                        )

                    [2] => Array(
                            [product_name] => Jaguar
                        )

                    [3] => Array(
                            [product_name] => Jeep
                        )))

    [1] => Array (
            [category_name] => Bike
            [product_name] => Array
                (
                    [0] => Array
                        (
                            [product_name] => Ducati
                        )) )

然后回显到html列表:

汽车: - 宝马 -丰田 -美洲虎 -吉普车

自行车: -杜卡迪

请帮助。.谢谢

3 个答案:

答案 0 :(得分:3)

这是您的摘录,请参阅内联文档以获取说明

$temp = [];
foreach ($arr as $key => $value) {
    $temp[$value['category_name']]['category_name']  = $value['category_name']; // first category assigned
    $temp[$value['category_name']]['product_name'][] = $value['product_name']; // grasping all values for same category name
}
foreach ($temp as $key => $value) {
    echo $value['category_name'].':- '. implode(" - ", $value['product_name']).'<br>'; // creation of string
}

正在工作demo

答案 1 :(得分:0)

希望有帮助。

$t = [];
foreach($input_array as $v) {
    $t[$v['category_name']] [] = $v['product_name'];
}
$out = [];
foreach ($t as $key => $val) {
        $out[$key] = implode(',',$val);
}
echo $out['car'];
echo "\n";
echo $out['bike'];

答案 2 :(得分:0)

您可以使用array_maparray_column

$res=[];
array_map(function($v) use (&$res){
  $res[$v['category_name']][] = ['product_name' => $v['product_name']];
}, $arr);
foreach($res as $type => $value){
 echo $type.':-'.implode(',',array_column($value, 'product_name'));
}

Live Demo