Home  >  Article  >  Backend Development  >  Algorithm - How to merge duplicate elements of an array into a new array in php?

Algorithm - How to merge duplicate elements of an array into a new array in php?

WBOY
WBOYOriginal
2016-12-01 00:56:201559browse

Suppose the current array is
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')
)
How to merge the value of key2 into a new one when the value of key1 in this array is the same? array. Please write a method to convert the original array into the following array
array(
0=>array('value1'=>array('value2','value3')),
1=>array('value2'= >array('value4','value5')),
...
)

Reply content:

Suppose the current array is
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')
)
How to merge the value of key2 into a new one when the value of key1 in this array is the same? array. Please write a method to convert the original array into the following array
array(
0=>array('value1'=>array('value2','value3')),
1=>array('value2'= >array('value4','value5')),
...
)

Question, is it independent regardless of whether key1 is repeated? Here’s how to do it

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

I think it would be much better if you change the array organization form
Of course, if you can't change it, it will be very hard,
For example, use traversal to do it

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn