具有密钥php的多维组的多维对象

时间:2015-03-21 20:07:37

标签: php arrays json

我有区域,街道和地址的城市列表,但我需要将它们分组为嵌套对象,如果它们具有相同的名称,则需要将它们分组。

我有多个城市的对象,详情如下:

{
    "City": [
        {
            "area": "some name",
            "colony": "some name",
            "street": "some name",
            "home": "some name"
        }
    ]
}

我需要将这些细节分组为多维对象中的多维对象。

最终结果

{
    "City": [
        {
            "area": [
                {
                    "colony": [
                        {
                            "street": [
                                {
                                    "home": "my-home"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。但无论如何,谢谢你的努力。解决方案:

$city = $jsonObject;
$array1 = array();
foreach ($city as $object => $element) {
    $array[$element['city']][] = [ 'area' => $element['area'], 'colony' => $element['colony'], 'home' => $element['home'];
}
$array2 = array();
foreach ($array1 as $object => $element) {
    foreach ($element as $key => $value) {
        $array1[$object][$value['area']][] = [ 'colony' => $value['colony'], 'home' => $value['home'];
    }
}
$array3 = array();
foreach ($array2 as $object => $element) {
    foreach ($element as $key => $value) {
        foreach ($value as $row => $column) {
            $array3[$object][$key][$column['colony']][] = [ 'home' => $value['home'];
        }
    }
}