Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> [PHP]konwersja tablicy - utworzenie zagnieżdzeń
wpaski
post 12.03.2019, 15:38:07
Post #1





Grupa: Zarejestrowani
Postów: 206
Pomógł: 6
Dołączył: 25.12.2011

Ostrzeżenie: (0%)
-----


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
Go to the top of the page
+Quote Post
skleps
post 12.03.2019, 16:21:56
Post #2





Grupa: Zarejestrowani
Postów: 142
Pomógł: 9
Dołączył: 3.03.2011

Ostrzeżenie: (0%)
-----


  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

Ten post edytował skleps 12.03.2019, 16:23:35
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 16.04.2024 - 05:10