Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [PHP]konwersja tablicy - utworzenie zagnieżdzeń
Forum PHP.pl > Forum > Przedszkole
wpaski
Mam taką tablice

  1. $list1= array(
  2. 0 => array(
  3. 'region' => 'germany',
  4. 'number' => 3,
  5. 'name' => 'test1',
  6. 'color' => 'green',
  7. 'anotherthing' => 'anotherthing'
  8. ),
  9. 1 => array(
  10. 'region' => 'germany',
  11. 'number' => 3,
  12. 'name' => 'test1',
  13. 'color' => 'green',
  14. 'anotherthing' => 'anotherthing'
  15. ),
  16. 2 => array(
  17. 'region' => 'france',
  18. 'number' => 4,
  19. 'name' => 'test2',
  20. 'color' => 'yellow',
  21. 'anotherthing' => 'anotherthing'
  22. ),
  23. );

A chcę:
  1. $list2 = array(
  2. 0 => array(
  3. 'region' => 'germany',
  4. 'number' => 3,
  5. 'name' => 'test1',
  6. 'list' => array(
  7. 0 => array(
  8. 'color' => 'green',
  9. 'anotherthing' => 'anotherthing'
  10. ),
  11. 1 => array(
  12. 'color' => 'green',
  13. 'anotherthing' => 'anotherthing'
  14. )
  15. )
  16. ),
  17. 1 => array(
  18. 'region' => 'france',
  19. 'number' => 4,
  20. 'name' => 'test2',
  21. 'list' => array(
  22. 0 => array(
  23. 'color' => 'yellow',
  24. 'anotherthing' => 'anotherthing'
  25. )
  26. )
  27. )
  28. );


Jak to zrobić? Chodzi o to, żeby w kluczu 'list' były dane które mają klucz 'number' taki sam
skleps
  1. $list2 = array();
  2. foreach ($list1 as $row) {
  3. $list2[$row['number']]['region'] = $row['region'];
  4. $list2[$row['number']]['name'] = $row['name'];
  5. $list2[$row['number']]['number'] = $row['number'];
  6. $list2[$row['number']]['list'][] = array(
  7. 'color' => $row['color'],
  8. 'anotherthing' => $row['anotherthing']
  9. );
  10. }
  11. echo '<pre>'.print_r($list2,1).'</pre>';
  12. // list2 jako klucze ma "number", jeśli tego nie chcemy na pewno to:
  13. $list2 = array_values($list2);
  14. echo '<pre>'.print_r($list2,1).'</pre>';


Nie wiem jak pewny jesteś danych wejściowych w polach 'region' i 'name' bo jak widzisz powyższe nadpisuje i zostaną wartości z ostatniej iteracji. Można by dopisać sprawdzenia różnic i ew zgłoszenie błędu ale to już twoja inwencja
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.