簡體   English   中英

使用 PHP 在 JSON 中添加鍵值

[英]Add Key to Value in JSON with PHP

我正在使用的 API 格式化其 JSON,而沒有對象值的KEY 它的格式更像是一個數組。 作為參考,這是我嘗試使用的 API 的鏈接https://opensky-network.org/apidoc/rest.html 下面是 JSON 的示例。

錯誤的例子

{
    "time": 1535758880,
    "states": [
        [
            "First",
            "A"
        ],
        [
            "Second",
            "B"
        ]       
    ]
}

上面的 JSON 也有每個對象的方括號。 這在我的情況下不起作用。 它們需要是大括號。 下面是我試圖實現的一個例子。 請注意,對象括號是卷曲的,並且每個值都有一個鍵。

需要的例子

{
    "time": 1535758880,
    "states": [
        {
            "id": "First",
            "content": "A"
        },
        {
            "id": "Second",
            "content": "B"
        }       
    ]
}

這是我目前正在編寫的用於在 JSON 中查找值的代碼。

<?php
$str = '
{
    "time": 1535758880,
    "states": [
        {
            "id": "First" ,
            "content": "A"
        },
        {
            "id": "Second" ,
            "content": "B"
        }       
    ]
}';

$json = json_decode($str);
foreach($json->states as $item)
{
    if($item->id == "Second")
    {
        echo $item->content;  
    }
}
?>

我的總體問題是,如何將idcontent添加到我的 JSON 並用大括號替換每個對象的方括號? 我想我需要以某種方式做一個 str_replace() 。 但我不確定如何處理這個問題。

您需要重新轉換數組,然后將其重新編碼回 json。 像這樣的東西:

$formatted = json_decode($str);
foreach ($formatted->states as $key => $value) {
    $tmp = array(
        'id' => $value[0],
        'content' => $value[1]
    );
    $formatted->states[$key] = $tmp;
}

// If you want this in array format you are done here, just use $formatted.

// If you want this back in json format, then json_encode it.
$str = json_encode($formatted);

絕對不要嘗試字符串替換。

首先,我會質疑您是否真的需要從數組到對象的轉換。 $item[0]並不比$item->id差多少。 如果你真的想要,你可以讓你的代碼更明顯,並為索引創建變量。

$id = 0;
$content = 1;

if ($item[$id] == 'Second') {
    echo $item[$content];
}

但是,如果由於某種原因您不得不轉換,您可以使用上面的 mopsyd 帖子中的代碼

暫無
暫無

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

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