簡體   English   中英

Json使用數組的內容解碼

[英]Json decode using content of array

我正在訓練自己(JSON和PHP),但遇到一個問題,我讓Json解碼如下:

"playerstats": {
    "steamID": "75068112",
    "gameName": "ValveTestApp260",
    "stats": [
        {
            "name": "total_kills",
            "value": 2314497
        },
        {
            "name": "total_deaths",
            "value": 1811387
        },

並解析成PHP我做:

$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo  $json['playerstats']['stats'][1]['name']

它有效,但是問題是當我更改id以獲取統計信息時,數組的順序不相同:/所以我不能使用[2]或任何其他數字來獲取數據。

我在這里發布信息,以了解如何使用每個數組的屬性名稱(例如'total_kills' )而不是[1] .. [2]來獲取統計信息。

感謝您的支持

使用foreach並使用if條件檢查名稱是否為'total_kills'為true,然后將其存儲到這樣的新數組中。

    <?php
    $json = json_decode($content, true);
    $new_array =array();
    $i=0;
    foreach($json['playerstats']['stats'] as $row )
    { 

        if($row['name']=='total_kills')
        {

            $new_array[]=array($row['name']=>$row['value']);
        }

        if($i<10)
        {

           break;   
        }
        $i++
    } 

    print_r($new_array);
    ?>
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);  

foreach($json['playerstats']['stats'] as $row )
{ 

 echo $row['name'];
 echo $row['value']; 

}

您正在尋找的是一種遍歷數組的方法。 在PHP中,您可以執行以下操作;

$url = 'myurl';
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json["playerstats"]["stats"] as $stat){
    if($stat["name"] == "total_kills"){
        echo "total kills: ".$stat["value"];
    }
    elseif($stat["name"] == "total_deaths"){
        // ...
    }
    // etc... continue to select all parameters you would like
}

這將允許您使用if else語句獲取每個具有name統計信息的value

處理數組中所有對象的另一種方法是使用array_map()函數,該函數將另一個函數作為其參數之一。 盡可能使用它會迫使您遵守良好的編程習慣,因為傳入的函數無法修改數組之外的值以及通過use傳入的參數。

暫無
暫無

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

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