簡體   English   中英

在PHP中從JSON獲取數據

[英]Getting Data From JSON in PHP

我試圖以這種JSON格式獲取數據以便能夠在屏幕上顯示問題,因為我嘗試了多種方法,例如:我不確定如何做到這一點:

$stats = json_decode($result);
// var_dump($stats);
echo $stats->elo;

而且由於[]而沒有任何效果,我不確定如何獲取數據,因為我以前從未使用過它。 如下所示,這是我需要獲取的一小部分數據。

[{"_id":{"championId":51,"role":"DUO_CARRY"},"elo":"BRONZE","patch":"7.11","championId":51,"positions":{"deaths":3,"winRates":6,"minionsKilled":2,"previousOverallPerformanceScore":6}}]

提前致謝

處理JSON時有一個簡單的經驗法則。 首先,只需對其進行解碼並使用print_r()打印,即可輕松查看其結構

$s = '[{"_id":{"championId":51,"role":"DUO_CARRY"},"elo":"BRONZE","patch":"7.11","championId":51,"positions":{"deaths":3,"winRates":6,"minionsKilled":2,"previousOverallPerformanceScore":6}}]';

$stats = json_decode($s);

print_r($stats);

在這種情況下將向您顯示

Array
(
    [0] => stdClass Object
        (
            [_id] => stdClass Object
                (
                    [championId] => 51
                    [role] => DUO_CARRY
                )
            [elo] => BRONZE
            [patch] => 7.11
            [championId] => 51
            [positions] => stdClass Object
                (
                    [deaths] => 3
                    [winRates] => 6
                    [minionsKilled] => 2
                    [previousOverallPerformanceScore] => 6
                )
        )
)

所以現在您知道有一個數組,在這種情況下僅包含一個對象

因此,要展示elo您可以做一個簡單的

echo $stats[0]->elo;    // BRONZE

但是由於它是一個對象數組,所以最好在某些情況下假設會有多個統計信息,因此您可以像這樣在foreach循環中對其進行處理

foreach ($stats as $stat) {
    echo $stat->elo;
}

如果在該json中獲得多個數組數據,請使用foreach,如下所示

foreach ($stats as $row) {
    echo $row->elo;
}

如果只想獲取第一條記錄,則使用$stats[0]->elo;

如果我正確地理解了您(您想獲取數組中的數據?),那就不知道,但是嘗試

$stats = json_decode($result,true);
var_dump($stats);

您的json_decode輸出是一個對象數組。 因此,您必須先使用索引來訪問數組元素,然后使用$array[0]->elo Live演示訪問對象的屬性

$string = '[{"_id":{"championId":51,"role":"DUO_CARRY"},"elo":"BRONZE","patch":"7.11","championId":51,"positions":{"deaths":3,"winRates":6,"minionsKilled":2,"previousOverallPerformanceScore":6}}]';
print_r(json_decode($string)[0]->elo);

如果要獲取關聯數組,則應使用$stats = json_decode($result, true); var_dump($stats); $stats = json_decode($result, true); var_dump($stats); 你會得到

array (size=1)
  0 => 
    array (size=5)
      '_id' => 
        array (size=2)
          'championId' => int 51
          'role' => string 'DUO_CARRY' (length=9)
      'elo' => string 'BRONZE' (length=6)
      'patch' => string '7.11' (length=4)
      'championId' => int 51
      'positions' => 
        array (size=4)
          'deaths' => int 3
          'winRates' => int 6
          'minionsKilled' => int 2
          'previousOverallPerformanceScore' => int 6

為了獲取元素,可以通過$stats[0]或with loop獲取數組的第一個鍵。 例如 $stats[0]['elo']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM