Flattening a JSON multi depty array in PHP

后端 未结 2 779
挽巷
挽巷 2021-01-14 11:38

Good morning, given the below data structure (in JSON for ease of reading)

[
{
    \"parent\": \"root\",
    \"active\": \"1\",
    \"label\": \"Index\",
            


        
2条回答
  •  生来不讨喜
    2021-01-14 11:54

    Not very hard:

    function flatten(array $array) {
        $branch = [];
    
        foreach ($array as $item) {
            $children = [];
            if (isset($item['children']) && is_array($item['children'])) {
                $children = flatten($item['children']);
                unset($item['children']);
            }
            $branch = array_merge($branch, [$item], $children);
        }
    
        return $branch;
    }
    

提交回复
热议问题