时间:2021-07-01 10:21:17 帮助过:17人阅读
假设当前数组为
array(
0=>array('key1'=>'value1' , 'key2'=>'value2'),
1=>array('key1'=>'value1' , 'key2'=>'value3'),
2=>array('key1'=>'value2' , 'key2'=>'value4'),
...
999=>array('key1'=>'value2' , 'key2'=>'value5')
)
如何将这个array中 key1的value 相同的情况下 将key2的value合并成一个新的数组。求写一个方法将原数组转化问 如下数组
array(
0=>array('value1'=>array('value2','value3')),
1=>array('value2'=>array('value4','value5')),
...
)
题主,是无论 key1
是否有重复都独立吗?下面是这样的做法
$arr = array(
0=>array('key1'=>'value1' , 'key2'=>'value2'),
1=>array('key1'=>'value1' , 'key2'=>'value3'),
2=>array('key1'=>'value2' , 'key2'=>'value4'),
999=>array('key1'=>'value2' , 'key2'=>'value5')
);
$result = array();
foreach ($arr as $data) {
isset($result[$data['key1']]) || $result[$data['key1']] = array();
$result[$data['key1']][] = $data['key2'];
}
print_r($result);
//
输出如下
Array
(
[value1] => Array
(
[0] => value2
[1] => value3
)
[value2] => Array
(
[0] => value4
[1] => value5
)
)
我觉得你换一种数组组织形式会好很多
当然如果不能换的话会非常辛苦,
比如用遍历去做