1. 程式人生 > >PHP合並某個字段相同的數組,並重組數據算法

PHP合並某個字段相同的數組,並重組數據算法

算法 字數 class tinc 字符串 urn keyword pub _array

  1. 對數組$array重組:
  2. $array = array(
  3. array(‘id‘=>1,‘name‘=>‘aa‘,‘pwd‘=>‘12‘),
  4. array(‘id‘=>1,‘name‘=>‘bb‘,‘pwd‘=>‘56‘),
  5. array(‘id‘=>1,‘name‘=>‘saa‘,‘pwd‘=>‘89‘),
  6. array(‘id‘=>2,‘name‘=>‘cc‘,‘pwd‘=>‘78‘)
  7. );
  8. 實現代碼如下:
  9. $tmpArray = array();
  10. foreach ($array as $row) {
  11. $key = $row[‘id‘];
  12. if (array_key_exists($key, $tmpArray)) {
  13. //$tmpArray[$key][‘pwd‘] = $tmpArray[$key][‘pwd‘] . ‘,‘ . $row[‘pwd‘]; //用這句的話下面有關pwd的條件語句都要刪掉,實現其字符串形式
  14. if (is_array($tmpArray[$key][‘name‘])) {
  15. $tmpArray[$key][‘name‘][] = $row[‘name‘];
  16. } else {
  17. $tmpArray[$key][‘name‘] = array($tmpArray[$key][‘name‘], $row[‘name‘]);
  18. }
  19. if (is_array($tmpArray[$key][‘pwd‘])) {
  20. $tmpArray[$key][‘pwd‘][] = $row[‘pwd‘];
  21. } else {
  22. $tmpArray[$key][‘pwd‘] = array($tmpArray[$key][‘pwd‘], $row[‘pwd‘]);
  23. }
  24. } else {
  25. $tmpArray[$key] = array(‘id‘=>$row[‘id‘],‘name‘=>array($row[‘name‘]),‘pwd‘=>array($row[‘pwd‘])); //此句要註意,可設置
  26. // $tmpArray[$key] = $row; // 有字段相加時可能會代替上面一句
  27. }
  28. }
  29. echo "<pre>";
  30. var_dump($tmpArray);
  31. 打印結果為:
  32. array (size=2)
  33. 1 =>
  34. array (size=3)
  35. ‘id‘ => int 1
  36. ‘name‘ =>
  37. array (size=3)
  38. 0 => string ‘aa‘ (length=2)
  39. 1 => string ‘bb‘ (length=2)
  40. 2 => string ‘saa‘ (length=3)
  41. ‘pwd‘ =>
  42. array (size=3)
  43. 0 => string ‘12‘ (length=2)
  44. 1 => string ‘56‘ (length=2)
  45. 2 => string ‘89‘ (length=2)
  46. 2 =>
  47. array (size=3)
  48. ‘id‘ => int 2
  49. ‘name‘ =>
  50. array (size=1)
  51. 0 => string ‘cc‘ (length=2)
  52. ‘pwd‘ =>
  53. array (size=1)
  54. 0 => string ‘78‘ (length=2)
  1. // $field 為一維數字數組,$field[0]為用於分組的單一字段。
  2. public function combine($array,$field){
  3. $tmpArray = array();
  4. $distinct_field = $field[0];
  5. unset($field[0]);
  6. foreach ($array as $row) {
  7. $key = $row[$distinct_field];
  8. if (array_key_exists($key, $tmpArray)) {
  9. foreach($field as $value){
  10. if (is_array($tmpArray[$key][$value])) {
  11. $tmpArray[$key][$value][] = $row[$value];
  12. } else {
  13. $tmpArray[$key][$value] = array($tmpArray[$key][$value], $row[$value]);
  14. }
  15. }
  16. } else {
  17. $tmpArray[$key][$distinct_field] = $row[$distinct_field];
  18. foreach ($field as $value){
  19. $tmpArray[$key][$value] = array($row[$value]);
  20. }
  21. }
  22. }
  23. return $tmpArray;
  24. }

PHP合並某個字段相同的數組,並重組數據算法