一个php的数组转换问题 如何将一维数组按要求转为多维

呼噜噜噜 发布于 2015/05/25 20:58
阅读 1K+
收藏 1
PHP
 有这样一个数组 它的每一项中的store_id和store_name都是一样的 是从数据库里join查询出来的
Array
(
    [0] => Array
        (
            [store_id] => 3
            [store_name] => 店铺1
            [brand_id] => 395
            [brand_name] => 茶王星
        )

    [1] => Array
        (
            [store_id] => 3
            [store_name] => 店铺1
            [brand_id] => 396
            [brand_name] => 全能
        )

    [2] => Array
        (
            [store_id] => 3
            [store_name] => 店铺1
            [brand_id] => 397
            [brand_name] => 绿植物龙
        )

我想将它的brand那部分合并 变成类似这样输出 应该怎么做
Array
(
    [0] => Array
        (
            [store_id] => 3
            [store_name] => 店铺1
            [brand]=>array
            (
                [0]=>array(
                    [brand_id] => 395
                    [brand_name] => 茶王星
                )
                [1]=>array(
                    [brand_id] => 396
                    [brand_name] => 全能
                )
                [2]=>array(
                    [brand_id] => 397
                    [brand_name] => 绿植物龙
                )
            )
        )
)
加载中
0
eechen
eechen
<?php
$arr = array(
    0 => array(
        'store_id' => 3,
        'store_name' => '店铺1',
        'brand_id' => 395,
        'brand_name' => '茶王星'
        ),
    1 => array(
        'store_id' => 3,
        'store_name' => '店铺1',
        'brand_id' => 396,
        'brand_name' => '茶王星'
        ),
    2 => array(
        'store_id' => 3,
        'store_name' => '店铺1',
        'brand_id' => 397,
        'brand_name' => '绿植物龙'
        )
);
$new = array();
foreach($arr as $k => $v){
    $new[0]['store_id'] = $v['store_id'];
    $new[0]['store_name'] = $v['store_name'];
    $new[0]['brand'][$k]['brand_id'] = $v['brand_id'];
    $new[0]['brand'][$k]['brand_name'] = $v['brand_name'];
}
print_r($new);
//输出:
Array
(
    [0] => Array
        (
            [store_id] => 3
            [store_name] => 店铺1
            [brand] => Array
                (
                    [0] => Array
                        (
                            [brand_id] => 395
                            [brand_name] => 茶王星
                        )

                    [1] => Array
                        (
                            [brand_id] => 396
                            [brand_name] => 茶王星
                        )

                    [2] => Array
                        (
                            [brand_id] => 397
                            [brand_name] => 绿植物龙
                        )

                )

        )

)
0
fieldinrain
fieldinrain

如果每一项中的store_id和store_name都是一样的话:(数组为空的话,事先判断一下)

$new =[[
  'store_id' => $arr[0]['store_id'],
  'store_name' => $arr[0]['store_name'],
  'brand' => array_map(function($item){
       return ['brand_id' => $item['brand_id'], 'brand_name' => $item['brand_name']];
  },$arr)
]];



返回顶部
顶部