Home >Backend Development >PHP Tutorial >Detailed explanation of how PHP allows groups of the same value in an array to form a new array
This article mainly shares with you an article in PHP to form a new array instance with the same value in the array. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor to take a look, I hope it can help everyone.
The example is as follows:
$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(); <span style="color:#FF0000;">foreach ($arr as $data) { isset($result[$data['key1']]) || $result[$data['key1']] = array(); $result[$data['key1']][] = $data['key2']; }</span> ksort($cityAr, SORT_NATURAL);//这个是键值按字母先后顺序排列 print_r($result); //输出如下 Array ( [value1] => Array ( [0] => value2 [1] => value3 ) [value2] => Array ( [0] => value4 [1] => value5 ) )
Related recommendations:
Detailed example of PHP array access interface ArrayAccess
In-depth understanding of the count function of PHP arrays
Example of php array combination and deduplication
The above is the detailed content of Detailed explanation of how PHP allows groups of the same value in an array to form a new array. For more information, please follow other related articles on the PHP Chinese website!