小编典典

按子数组值分组数组

algorithm

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

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 )
          )
)

阅读 266

收藏
2020-07-28

共1个答案

小编典典

$arr = array();

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

ksort($arr, SORT_NUMERIC);
2020-07-28