简体   繁体   English

根据PHP中的键合并数组

[英]Merge array according to key in PHP

I've got a huge list of arrays with 2 members which looks like that: 我有一个庞大的数组列表,其中包含2个成员,如下所示:

<?php
$aData = array ();
$aData[0] = array ( 14400, 'Item1' );
$aData[1] = array ( 14400, 'Item4' );
$aData[2] = array ( 14401, 'Item2' );
$aData[3] = array ( 14402, 'Item4' );
$aData[4] = array ( 14402, 'Item5' );
$aData[5] = array ( 14402, 'Item9' );

and I'd like to convert this into arrays like that: 我想将其转换成这样的数组:

$aData[0] = array ( 14400, 'Item1,Item4' );
$aData[1] = array ( 14401, 'Item4' );
$aData[2] = array ( 14402, 'Item4,Item5,Item9' );

Whereas the 2nd one could be a string or an array. 而第二个可以是字符串或数组。 Now I was trying to implement some logic - but is there a function that could do that at least partly? 现在,我正在尝试实现一些逻辑-但是是否有至少可以部分实现此功能的函数? array_map or array_merge_recursive don't seem to fit exactly? array_maparray_merge_recursive似乎不完全适合?

Use a Map of (int -> string list) 使用(int->字符串列表)的映射

for each (key,value) pair
    map.get(key).add(value)

What language are you using? 您使用什么语言?

Because you don't know what you you want. 因为你不知道自己想要什么。 You can easy receive such result' 您可以轻松收到这样的结果”

$arr = [
[14400,Item1],
[14400,Item4],
[14401,Item2],
[14402,Item4],
[14402,Item5],
[14402,Item9]
];

$new = [];
foreach($arr as $item) 
  $new[$item[0]][] = $item[1];

print_r($new);

result 结果

Array
(
[14400] => Array
        (
        [0] => Item1
        [1] => Item4
    )

[14401] => Array
    (
        [0] => Item2
    )

[14402] => Array
    (
        [0] => Item4
        [1] => Item5
        [2] => Item9
    )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM