按ID合并数组,并使用重复的关联索引说明唯一值

时间:2019-05-09 18:45:11

标签: php arrays

我的数组结构如下:

Array
(
    [platform] => Nintendo
    [console] => Nintendo NES
)
1
Array
(
    [platform] => Nintendo
    [console] => Super Nintendo
)
1
Array
(
    [platform] => Nintendo
    [console] => Nintendo 64
)
1
Array
(
    [platform] => Nintendo
    [console] => Gamecube
)
Array
(
    [platform] => Atari
    [console] => Atari 2600
)
1
Array
(
    [platform] => Atari
    [console] => Atari 5200
)
1
Array
(
    [platform] => Atari
    [console] => Atari 7800
)
Array
(
    [platform] => Sega
    [console] => Sega Master System
)
1
Array
(
    [platform] => Sega
    [console] => Sega Genesis
)
1
Array
(
    [platform] => Sega
    [console] => Sega CD
)

我想将控制台合并到各自平台下的数组中,并了解如何使用唯一索引来实现,但不能在相同的地方进行。我想要的输出将是这样的:

Array
(
    [Nintendo] => Array
        (
            [0] => Nintendo NES
            [1] => Super Nintendo
            [2] => Nintendo 64
            [3] => Gamecube
        )

    [Atari] => Array
        (
            [0] => Atari 2600
            [1] => Atari 5200
            [2] => Atari 7800
        )

    [Sega] => Array
        (
            [0] => Sega Master System
            [1] => Sega Genesis
            [2] => Sega CD
        )

)

我尝试了以下操作:

$new = [];
foreach($arr as $key => $value){
  if(is_array($value)){
    if( !array_key_exists($value['platform'],$new) ){
        $new[$value['platform']] = [];
    }  
    $new[$value['platform']] = array_merge($new[$value['platform']], $value );
  }
} 

但它仅返回每个平台中的最后一个控制台,因为它们没有唯一的控制台ID。是否需要使用正则表达式来查找匹配的平台名称和不匹配的控制台名称?我什至朝着正确的方向前进还是应该朝array_reducearray_walk前进?

1 个答案:

答案 0 :(得分:1)

不确定为什么要检查循环中是否为数组,可以删除该部分,然后使用[] ...将控制台添加到现有列表中。

$new = [];
foreach($arr as $key => $value){
    if( !array_key_exists($value['platform'],$new) ){
        $new[$value['platform']] = [];
    }  
    $new[$value['platform']][] = $value['console'] ;
}