PHP让数组中有相同值的组成新的数组实例

下面小编就为大家分享一篇PHP让数组中有相同值的组成新的数组实例,具有很好的参考价值,希望对大家有所帮助,一起跟随小编过来看看吧。

实例如下所示:

  1. $arr = array(
  2. 0=>array('key1'=>'value1' , 'key2'=>'value2'),
  3. 1=>array('key1'=>'value1' , 'key2'=>'value3'),
  4. 2=>array('key1'=>'value2' , 'key2'=>'value4'),
  5. 999=>array('key1'=>'value2' , 'key2'=>'value5')
  6. );
  7. $result = array();
  8. <span >foreach ($arr as $data) {
  9. isset($result[$data['key1']]) || $result[$data['key1']] = array();
  10. $result[$data['key1']][] = $data['key2'];
  11. }</span>
  12. ksort($cityAr, SORT_NATURAL);//这个是键值按字母先后顺序排列
  13. print_r($result);
  14. //输出如下
  15. Array
  16. (
  17. [value1] => Array
  18. (
  19. [0] => value2
  20. [1] => value3
  21. )
  22. [value2] => Array
  23. (
  24. [0] => value4
  25. [1] => value5
  26. )
  27. )