【问题标题】:iterate through array (recieved via json) to get values遍历数组(通过 json 接收)以获取值
【发布时间】:2016-10-24 15:05:47
【问题描述】:

我正在尝试获取某人连接到的 Steam 组的 ID。这是json输出:

{
    "response": {
        "success": true,
        "groups": [
            {
                "gid": "111"
            },
            {
                "gid": "222"
            },
            {
                "gid": "333"
            },
            {
                "gid": "444"
            },
            {
                "gid": "555"
            }
        ]

    }
}

我尝试过:

$groupIDs = $reply['response']['groups'];
foreach ($groupIDs as $gID) {
    // Do stuff
}

我收到以下错误,但我正在努力寻找如何纠正它。

Invalid argument supplied for foreach()

对不起,我没有说清楚。我已经在 foreach() 之前解码了。

    $reply = json_decode($reply, true);

【问题讨论】:

    标签: php arrays json foreach


    【解决方案1】:

    首先您必须使用 php 函数 json_decode 解码 json 字符串。然后迭代对象如下图

    $string = '{
        "response": {
            "success": true,
            "groups": [
                {
                    "gid": "111"
                },
                {
                    "gid": "222"
                },
                {
                    "gid": "333"
                },
                {
                    "gid": "444"
                },
                {
                    "gid": "555"
                }
            ]
    
        }
    }';
    $array = json_decode($string);
    
    foreach($array->response->groups as $value ){
        echo $value->gid;
        echo "<br/>";
    }
    

    【讨论】:

      【解决方案2】:

      http://php.net/manual/pt_BR/function.json-decode.php

      试试:

      $response = json_decode($reply, true);
      $groupIDs = $response['response']['groups'];
      foreach ($groupIDs as $gID) {
          // Do stuff
      }
      

      【讨论】:

      • "gid" 呢? $gID 听起来你已经拥有它们了!
      【解决方案3】:

      使用 json_decode($response) cf doc

      $rep = json_decode($response)
      foreach ($rep->response->groups as $gID) {
          // Do stuff
      }
      

      【讨论】:

        【解决方案4】:
        $groups = $reply['response']->groups;
        foreach ($groups as $group) {
            print $group->gid;
        }
        

        在json中,每个{}都被解析为对象,每个[]被解析为数组。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-11-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多