按子数组值对数组进行分组

2022-08-30 09:19:45

我有一个以下格式的子数组:

array
(
    a => array ( id = 20, name = chimpanzee )
    b => array ( id = 40, name = meeting )
    c => array ( id = 20, name = dynasty )
    d => array ( id = 50, name = chocolate )
    e => array ( id = 10, name = bananas )
    f => array ( id = 50, name = fantasy )
    g => array ( id = 50, name = football )
)

我想根据每个子数组中的id字段将其分组到一个新数组中。

array
(
    10 => array
          (
            e => array ( id = 10, name = bananas )
          )
    20 => array
          (
            a => array ( id = 20, name = chimpanzee )
            c => array ( id = 20, name = dynasty )
          )
    40 => array
          (
            b => array ( id = 40, name = meeting )
          )
    50 => array
          (
            d => array ( id = 50, name = chocolate )
            f => array ( id = 50, name = fantasy )
            g => array ( id = 50, name = football )
          )
)

答案 1
$arr = array();

foreach ($old_arr as $key => $item) {
   $arr[$item['id']][$key] = $item;
}

ksort($arr, SORT_NUMERIC);

答案 2
foreach($array as $key => $value){
   $newarray[$value['id']][$key] = $value;
}

var_dump($newarray);

小菜一碟 ;)