假設目前陣列為
array(
0=>array('key1'=>'value1' , 'key2'=>'value2'),
1=>array('key1'=>'value1value1
' , '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')),
...
假設目前陣列為
array(0=>array('key1'=>'value1
' , 'key2'=>'value2'),1=>array('key1'=>'value1
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')),
)
題主,是無論
是否有重複都獨立嗎?下面是這樣的做法
<code>$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 ) )</code>