2015-12-26 61 views
1

我想在每一個users元素的末尾添加一個新的鍵 - 值對:爲什麼鍵值對不會被添加?

<?php 
$json = '[ 
    { 
    "date": "2014-10-09T17:38:19Z", 
    "users": [ 
     { 
     "name": "Peter", 
     "age": 20 
     }, 
     { 
     "name": "Anne", 
     "age": 25 
     }, 
     { 
     "name": "William", 
     "age": 30 
     } 
    ] 
    } 
]'; 

addData ($json); 
function addData($json) { 
    $obj = json_decode ($json, true); 
    foreach ($obj as $items) { 
     foreach ($items ['users'] as $users) { 
      $array = array (
        "myKey" => "myValue" 
      ); 
      array_push ($users, $array); 
     } 
    } 
    $json = json_encode ($obj); 

    echo $json; 
} 
?> 

所以新json應該像

[ 
    { 
     "date":"2014-10-09T17:38:19Z", 
     "users":[ 
     { 
      "name":"Peter", 
      "age":20, 
      "myKey":"myValue" 
     }, 
     { 
      "name":"Anne", 
      "age":25, 
      "myKey":"myValue" 
     }, 
     { 
      "name":"William", 
      "age":30, 
      "myKey":"myValue" 
     } 
     ] 
    } 
] 

相反,我讓我的老json作爲輸出,沒有新的鍵值對。

+0

的[添加新的鍵/值對爲JSON在PHP]可能的複製(http://stackoverflow.com/questions/19447175/add-new-key-value-pair -in -json-in-php) – Core972

+0

@Core972不是重複的。 –

+0

通過引用迭代數組 – Steve

回答

3

從手動摘自約foreach

爲了能夠直接修改環路 上一頁$值內的數組元素與&。在這種情況下,該值將由 參考分配。

這樣,您可以編輯$items$users數組中的值。

我認爲你可以做這樣的:

addData ($json); 
function addData($json) { 
    $obj = json_decode ($json, true); 
    foreach ($obj as &$items) { 
     foreach ($items ['users'] as &$users) { 
      $users["mykey"] = "myValue"; 
     } 
    } 
    $json = json_encode ($obj); 
    echo $json; 
} 

會導致:

[{ 
    "date": "2014-10-09T17:38:19Z", 
    "users": [{ 
     "name": "Peter", 
     "age": 20, 
     "mykey": "myValue" 
    }, { 
     "name": "Anne", 
     "age": 25, 
     "mykey": "myValue" 
    }, { 
     "name": "William", 
     "age": 30, 
     "mykey": "myValue" 
    }] 
}] 
+0

嘗試提供更多的解釋,以瞭解您正在做什麼以及爲什麼它會起作用。 –

0

你的主要問題是的foreach提供陣列的副本而不是實際的數組,所以當你修改$用戶,而不是像你認爲的那樣修改$ json變量。試試下面,我爲可讀性

<?php 
$json = '[ 
    { 
    "date": "2014-10-09T17:38:19Z", 
    "users": [ 
     { 
     "name": "Peter", 
     "age": 20 
     }, 
     { 
     "name": "Anne", 
     "age": 25 
     }, 
     { 
     "name": "William", 
     "age": 30 
     } 
    ] 
    } 
]'; 

$updated = addData ($json); 
echo $updated; 

function addData($json) { 
    $ArrList = json_decode ($json, true); 

    foreach ($ArrList['users'] as $userKey => $user) { 
      $array = array (
        "myKey" => "myValue" 
      ); 
     $ArrList['users'][$userKey][] = $array; 
    } 

    $json = json_encode ($ArrList); 

    return $json; 
} 
?> 

改變的變量等名稱上面的代碼循環在你的結構你的用戶陣列和保持在foreach循環的關鍵舉行。然後,當我們有結構時,我們需要更新原始數組。

0

你應該通過引用傳遞$items$users陣列,像這樣:


function addData($json) { 

    $obj = json_decode ($json, true); 

    foreach ($obj as &$items) { 
     foreach ($items ['users'] as &$users) { 
      $users['myKey'] = 'myValue'; 
     } 
    } 
    $json = json_encode ($obj); 

    echo $json; 
} 
相關問題