PHP 提取用户名等于 JSON 字符串的特定部分

PHP Extracting a certain part of JSON string where username equals

我想知道如何从 JSON 字符串中只提取特定部分:

[
        {
                "ID": "132",
                "countrycode": "DE",
                "USERNAME": "CRC Titan2000",
                "Nickname": "^7[6S] ^1Titan",
                "Money": "550111",
                "Distance": "105692714",
                "Trip": "370839",
                "Bonus": "223",
                "Last Car": "RB4",
                "Last Position": "The Hills",
                "Server": "^7One"
        },
        {
                "ID": "1634",
                "countrycode": "ES",
                "USERNAME": "lobocop",
                "Nickname": "^4Leo ^1Messi",
                "Money": "12816",
                "Distance": "17091463",
                "Trip": "25682",
                "Bonus": "29",
                "Last Car": "MRT",
                "Last Position": "Bridge East",
                "Server": "^7One"
        },
        {
                "ID": "4240",
                "countrycode": "GB",
                "USERNAME": "Smacky",
                "Nickname": "^7^d^6o^7^s",
                "Money": "-532",
                "Distance": "1987579",
                "Trip": "7738",
                "Bonus": "51",
                "Last Car": "RB4",
                "Last Position": "The Hills",
                "Server": "^7One"
        },
        {
                "ID": "5467",
                "countrycode": "TR",
                "USERNAME": "excaTR",
                "Nickname": "^1Furkan^7Tr",
                "Money": "7363",
                "Distance": "17064283",
                "Trip": "15747",
                "Bonus": "31",
                "Last Car": "RB4",
                "Last Position": "Bridge East",
                "Server": "^7One"
        }
]

我只想拉"USERNAME" excaTR的"Last Position",其他的都忽略了。有点像 MySQL 查询,我想在其中回显最后一个位置 WHERE username='excaTR',而不是 PHP 和 JSON.

这是我试过的代码,但没有用

$json_stats = file_get_contents('<JSON string here>');
$stats_data = json_decode($json_stats, true);

foreach ($stats_data as $_SESSION['username'] => $location){
    echo $location['Last Position'];
}

您没有按应有的方式使用 foreach。 看看你的 JSON,你有一个对象数组。

所以你必须遍历你的数组,并检查你的对象值。

顺便说一下,在我的回答中,我使用 json_decode( ,false) 将结果强制为多维数组,仅供参考。

$json_stats = file_get_contents('<JSON string here>');
$stats_data = json_decode($json_stats, false);

foreach ($stats_data as $array) {
  if ($array['USERNAME'] == 'excaTR') {
    echo $array['Last Position'];
  }
}