我是PHP的新手,我有一个非常基本的问题,但无法找到答案。这是一个JSONObject示例:
{
"biome":"forest",
"id":"51134535488",
"animals":[
{"species":"bear", "age":"8", "gender":"male", "family":"mamal"},
{"species":"hawk", "age":"3", "gender":"female", "family":"bird"},
{"species":"elk", "age":"5", "gender":"male", "family":"mamal"},
{"species":"spider", "age":"0.3", "gender":"female", "family":"insect"}
]
}
其中有一个JSONArray,其中包含四个JSONObject。我将如何从JSONObject中仅获取JSONArray,然后进行foreach循环以获取所有内部行?我正在Lumen框架中工作,因此对Lumen的具体回答会非常感激(如果可以在Lumen中以其他方式完成)!
答案 0 :(得分:3)
例如,如果您要显示四种:
$json = '{
"biome":"forest",
"id":"51134535488",
"animals":[
{"species":"bear", "age":"8", "gender":"male", "family":"mamal"},
{"species":"hawk", "age":"3", "gender":"female", "family":"bird"},
{"species":"elk", "age":"5", "gender":"male", "family":"mamal"},
{"species":"spider", "age":"0.3", "gender":"female", "family":"insect"}
]
}';
foreach(json_decode($json)->animals as $animal) {
echo $animal->species . "\n";
}
答案 1 :(得分:2)
您可以在此处使用一些有用的行:
/* Set the json file directory */
$path = 'your path here';
/* here your json file name */
$jsonfile = 'youjsonfilename';
/* json decode */
$language = json_decode(file_get_contents($path . $jsonfile. '.json'));
然后,如果您的json文件如下所示:
{
"test": {
"test1" : "test2",
}
}
您必须在php中编写此行以打印“ test2”,例如:
<?php echo $language->test->test1; ?>
答案 2 :(得分:1)
如果您是从JSON字符串开始的,则意味着您的示例是PHP中的字符串变量,您可以执行以下操作:
$jsonString = '{"biome" : "forest", ...}';
$forest = json_decode($jsonString, true); // Passing true as a second argument converts the JSON string into an array, instead of a PHP object
$animals = $forest['animals']; // If you're sure animals is always an array, you can do the following for loop without any problems
foreach ($animals as $animal) {
var_dump($animal);
}