Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> JSON tree do płaskiej struktury
psw779
post
Post #1





Grupa: Zarejestrowani
Postów: 39
Pomógł: 0
Dołączył: 25.03.2006

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


Witam,

chciałbym z drzewa zapisanego rekurencyjnie w formacie JSON stworzyć strukturę płaską.

Próbkę pliku JSON załączam, a oczekiwany format miałby wyglądać tak (fragment):

id;parent_id
36;35
74;35
35;1
1:0
55;54
57;54
54;1
76:0
77:0

Oczywiście json_decode i ładowanie z pliku potrafię wykonać. Tylko co dalej...

JSON:
Kod
[
    {
        "id":1,
        "children":[
            {
                "id":35,
                "children":[
                    {
                        "id":36,
                        "children":[
                            
                        ]
                    },
                    {
                        "id":74,
                        "children":[
                            
                        ]
                    }
                ]
            },
            {
                "id":54,
                "children":[
                    {
                        "id":55,
                        "children":[
                            
                        ]
                    },
                    {
                        "id":57,
                        "children":[
                            
                        ]
                    }
                ]
            }
        ]
    },
    {
        "id":76,
        "children":[
            
        ]
    },
    {
        "id":77,
        "children":[
            
        ]
    }
]


Temat udało się rozwiązać następującym kodem:

  1.  
  2. $jsonArray = json_decode($jsonString, true);
  3.  
  4. function parseJsonArray($jsonArray, $parentID = 0)
  5. {
  6. $return = array();
  7. foreach ($jsonArray as $subArray) {
  8. $returnSubSubArray = array();
  9. if (isset($subArray['children'])) {
  10. $returnSubSubArray = parseJsonArray($subArray['children'], $subArray['id']);
  11. }
  12. $return[] = array('id' => $subArray['id'], 'parentID' => $parentID);
  13. $return = array_merge($return, $returnSubSubArray);
  14. }
  15.  
  16. return $return;
  17. }
  18.  
  19. print_r(parseJsonArray($jsonArray));
  20.  
Go to the top of the page
+Quote Post

Posty w temacie


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

 



RSS Aktualny czas: 22.08.2025 - 15:44