Home > Backend Development > PHP Tutorial > 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
Release: 2023-03-01 20:42:02
Original
1587 people have browsed it

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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template