1. ホーム
  2. php

[解決済み] サブアレイの値で配列をグループ化する

2022-02-19 10:55:14

質問

次のような形式の部分配列の配列があります。

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

解決方法は?

$arr = array();

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

ksort($arr, SORT_NUMERIC);