json数组到标准数组

时间:2013-03-23 03:24:51

标签: php arrays json forms decode

让我解释一下我的问题,我应该在显示联系表单之前调用Web服务,Web服务的返回是:

$items = json_decode('[{"location":[{"building":["Building1"],"name":"Location1"}],"name":"Organization1"},{"location":[{"building":["Building2"],"name":"location2"}],"name":"Organisation2"},{"location":[{"building":["Building3"],"name":"Location3"}],"name":"Organization3"}]');

在这里,我使用以下代码仅提取了组织,地点和建筑物:

foreach( $items as $each ){
    echo $each->location[0]->building[0];
    echo $each->location[0]->name;
    echo $each->name;
}

我希望以这种格式获取不同阵列中的组织,建筑物和位置的值:

("building1", "building2", "building3")
("organisation1", "organisation2", "organisation3")
("location1", "location2", "location3")

2 个答案:

答案 0 :(得分:1)

获取现有代码并稍微修改一下;

$buildings = array( );
$organisations = array( );
$locations = array( );
foreach( $items as $each ){
    $buildings[] = $each->location[0]->building[0];
    $organisations[] = $each->location[0]->name;
    $locations[] = $each->name;
}

结果现在位于顶部定义的变量中。 []只是告诉它将一个值附加到数组的末尾。

答案 1 :(得分:0)

这是你如何做到的:

$arrays = array();
$arrays['buildings'] = array(); // buildings
$arrays['organisations'] = array();
$arrays['locations'] = array();
foreach( $items as $each ){
    $arrays['buildings'][] = $each->location[0]->building[0];
    $arrays['organisations'][] = $each->location[0]->name;
    $arrays['locations'][] = $each->name;
}