【问题标题】:How do I retrieve json array row from a json object?如何从 json 对象中检索 json 数组行?
【发布时间】:2019-02-27 20:41:14
【问题描述】:

我是 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 循环它以获取所有内部行?我在流明框架中工作,因此非常感谢特定的流明答案(如果它可以在流明中以不同的方式完成)!

【问题讨论】:

标签: php arrays json lumen


【解决方案1】:

例如,如果您想显示四个物种:

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

【讨论】:

    【解决方案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; ?>
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2016-11-13
        • 1970-01-01
        • 2017-02-25
        • 1970-01-01
        • 1970-01-01
        • 2020-06-08
        • 2019-03-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多