Php 如何从json对象检索json数组行?

Php 如何从json对象检索json数组行?,php,arrays,json,lumen,Php,Arrays,Json,Lumen,我是PHP新手,我有一个非常基本的问题,我无法找到答案。这是一个示例JSONObject: { "biome":"forest", "id":"51134535488", "animals":[ {"species":"bear", "age":"8", "gender":"male", "family":"mamal"}, {"species":"hawk", "age":"3", "gender":"female", "family":

我是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循环它以获取所有内部行?我是在流明框架下工作的,所以如果可以在流明中做不同的事情,那么一个特定的流明答案将是非常值得赞赏的

例如,如果要显示四种:

$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";
}

如果您从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);
}

以下是一些您可以使用的有用行:

/* 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; ?>
可能重复的