仅打印数组中某些键的值

时间:2013-01-28 08:56:30

标签: php arrays json foreach

我有这个源文件。

[
    {
        "title": "Course1",
        "location": "BuildingA",
        "day": "wednesday",
        "id": 85412
    },
    {
        "title": "Course2",
        "location": "BuidlingB",
        "day": "friday",
        "id": 85413
    },
    {
        "title": "Course3",
        "location": "BuidlingA",
        "day": "friday",
        "id": 85414
    }
]

我怎样才能在PHP中只打印键'title'和'location'的值?

我到目前为止的代码是:

$array = json_decode($json, true);

foreach ($array as $key => $jsons) {
     foreach($jsons as $key => $value)  
echo $value." ";
}

2 个答案:

答案 0 :(得分:1)

foreach ($array as $key => $jsons) {     
echo $jsons['title'];
echo $jsons['location'];
}

答案 1 :(得分:0)

$json = '
[
    {
        "title": "Course1",
        "location": "BuildingA",
        "day": "wednesday",
        "id": 85412
    },
    {
        "title": "Course2",
        "location": "BuidlingB",
        "day": "friday",
        "id": 85413
    },
    {
        "title": "Course3",
        "location": "BuidlingA",
        "day": "friday",
        "id": 85414
    }
]
';

$array = json_decode($json, true);

foreach ($array as $key => $jsons) {
echo $jsons["location"];
echo $jsons["title"];
}