按列对二维数组的行进行分组,并将除分组列之外的所有列推送到分组子数组中[重复]

问题描述 投票:0回答:1

我想重新组合我的阵列。我有以下内容:

[
    ['name' => 'test1', 'item_id' => 1, 'category' => 'cat1'],
    ['name' => 'test2', 'item_id' => 2, 'category' => 'cat1'],
    ['name' => 'test3', 'item_id' => 3, 'category' => 'cat1'],
    ['name' => 'test4', 'item_id' => 4, 'category' => 'cat2'],
]

我想像这样重新组合:

[
    'cat1' => [
        ['name' => 'test1', 'item_id' => 1],
        ['name' => 'test2', 'item_id' => 2],
        ['name' => 'test3', 'item_id' => 3],
    ],
    'cat2' => [
        ['name' => 'test4', 'item_id' => 4],
    ],
]

有人可以告诉我如何最好地做到这一点吗?

php arrays multidimensional-array grouping sub-array
1个回答
4
投票

只需循环它并重新组合它......例如:

$array = array(
    array(
        'name'      =>  'test1',
        'itemd_id'  =>  1,
        'category'  =>  'cat1',
    ),
    array(
        'name'      =>  'test2',
        'itemd_id'  =>  2,
        'category'  =>  'cat1',
    ),
    array(
        'name'      =>  'test3',
        'itemd_id'  =>  3,
        'category'  =>  'cat1',
    ),
    array(
        'name'      =>  'test4',
        'itemd_id'  =>  4,
        'category'  =>  'cat2',
    ),
);

$newArray = array();

foreach($array as $arrayKey => $arrayElement){
    $tmpCat = $arrayElement['category'];
    unset($arrayElement['category']);
    $newArray[$tmpCat][] =  $arrayElement;

}


var_dump($newArray);

array(2) {
  ["cat1"]=>
  array(3) {
    [0]=>
    array(2) {
      ["name"]=>
      string(5) "test1"
      ["itemd_id"]=>
      int(1)
    }
    [1]=>
    array(2) {
      ["name"]=>
      string(5) "test2"
      ["itemd_id"]=>
      int(2)
    }
    [2]=>
    array(2) {
      ["name"]=>
      string(5) "test3"
      ["itemd_id"]=>
      int(3)
    }
  }
  ["cat2"]=>
  array(1) {
    [0]=>
    array(2) {
      ["name"]=>
      string(5) "test4"
      ["itemd_id"]=>
      int(4)
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.