PHP - 解码JSON数组并在foreach循环中使用

use*_*377 -1 php arrays foreach json

我正在使用API​​并将JSON数组解码为PHP数组,但是当我使用foreach循环时它没有给我特定的值.这是原始JSON数组的片段:

"playerCredentials": {
    "observerEncryptionKey": "blahblah",
    "dataVersion": 0,
    "playerId": 8675309,
    "serverPort": 0,
    "observer": true,
    "summonerId": 0,
    "championId": 0,
    "observerServerIp": "111.111.111.111",
    "gameId": 123456789,
    "observerServerPort": 4388,
    "lastSelectedSkinIndex": 0
  },
Run Code Online (Sandbox Code Playgroud)

然后,我运行了这段代码:

$array = json_decode($json_array, true);
Run Code Online (Sandbox Code Playgroud)

然后将上述内容变为:

    { ["playerCredentials"]=> array(11) 
    { 
    ["observerEncryptionKey"]=> string(32) "blahblah" 
    ["dataVersion"]=> int(0) 
    ["playerId"]=> int(8675309) 
    ["serverPort"]=> int(0) 
    ["observer"]=> bool(true) 
    ["summonerId"]=> int(0) 
    ["championId"]=> int(0) 
    ["observerServerIp"]=> string(14) "111.111.111.111" 
    ["gameId"]=> int(123456789) 
    ["observerServerPort"]=> int(4338) 
    ["lastSelectedSkinIndex"]=> int(0) 
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我运行这个foreach循环时:

foreach($array['playerCredentials'] as $stats) {
echo $stats['playerId'];
}
Run Code Online (Sandbox Code Playgroud)

我得到的所有回报是82(我甚至不知道它来自哪里).但是,如果我运行这个:

foreach($array['playerCredentials'] as $stats) {
    echo $stats."<br>";
}
Run Code Online (Sandbox Code Playgroud)

我得到了整个数组中的所有信息:

blahblah
0
8675309
0
true
0
0
111.111.111.111
123456789
4338
0
Run Code Online (Sandbox Code Playgroud)

我怎么才能得到一件呢?

{
  "playerCredentials": {
    "observerEncryptionKey": "blahblah",
    "dataVersion": 0,
    "playerId": 8675309,
    "serverPort": 0,
    "observer": true,
    "summonerId": 0,
    "championId": 0,
    "observerServerIp": "111.111.111.111",
    "gameId": 1347503269,
    "observerServerPort": 8088,
    "lastSelectedSkinIndex": 0
  },
  "dataVersion": 0,
  "gameName": "match-1347503269",
  "reconnectDelay": 0,
  "game": {
    "practiceGameRewardsDisabledReasons": {
      "array": []
    },
    "glmSecurePort": 0,
    "queuePosition": 0,
    "playerChampionSelections": {
      "array": [
        {
          "spell1Id": 4,
          "spell2Id": 7,
          "championId": 25,
          "summonerInternalName": "nameone",
          "selectedSkinIndex": 0,
          "dataVersion": 0
        },
        {
          "spell1Id": 12,
          "spell2Id": 4,
          "championId": 13,
          "summonerInternalName": "nametwo",
          "selectedSkinIndex": 0,
          "dataVersion": 0
        }
]
Run Code Online (Sandbox Code Playgroud)

Geo*_*ton 5

在循环中,$stats指的是数组中每个元素的值.我想你在找$array['playerCredentials']['playerId'];.如果要迭代播放器的所有属性,可以执行以下操作:

foreach ($array['playerCredentials'] as $key => $value) {
    printf('%s => %s<br />', $key, $value);
}
Run Code Online (Sandbox Code Playgroud)