【问题标题】:Fetching JSON data square brackets获取 JSON 数据方括号
【发布时间】:2015-05-15 21:13:45
【问题描述】:

我想知道如何从包含方括号的 JSON 文件中获取 JSON 数据。我有一个这样的 JSON 代码:

"events": [
    {
        "id": 462467,
        "eventDetails": [
            70,
            1,
            [
                "Swansea City - Manchester City",
                "Swansea City - Manchester City",
                "Swansea-ManCity"
            ],

我正在使用 foreach 语句来获取“eventDetails”的值,但我怎样才能整理出数字“1”,并分别获取每个团队名称? 我要执行的 php 语句是:如果第二个值为“1”,则获取团队名称。

这是我目前所拥有的:

 foreach($array2['events'] as $key=>$val)

    {     
         foreach($val['eventDetails'] as $values)
         {

            if ($values['70,1']) { echo "test"; }

         }
    } 

【问题讨论】:

  • 使用json_decode()函数即可。

标签: php json


【解决方案1】:

您可以尝试像这样使用file_get_contents()

$content = file_get_contents( $filename );
$json = json_decode( $content );
print_r( $json );

更多信息在这里:

https://php.net/manual/en/function.file-get-contents.php

这里:

https://php.net/manual/en/function.json-decode.php

【讨论】:

  • 我如何使用 json_decode 来分别获取例如团队名称? json_decode 返回Array ( [0] => Swansea City - Manchester City [1] => Swansea City - Manchester City [2] => Swansea-ManCity )
【解决方案2】:

在 json 括号中表示 stdClass (object) ,所以:

foreach($array2->events as $key=>$val){    
    echo($val->eventDetails[0]);//70
    echo($val->eventDetails[1]);//1
    foreach($val->eventDetails[2] as $team)
         echo $team;
} 

【讨论】:

  • “echo $team”正在输出所有三个团队数据Swansea City - Manchester CitySwansea City - Manchester CitySwansea-ManCity。如何获取 Swansea 的一个值和 ManCity 的一个值?
  • 使用 array_unique() 函数删除重复值。
猜你喜欢
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
相关资源
最近更新 更多