我正在尝试将新的KEY / VALUE添加到现有的Array中。我遇到了困难,因为我看到了其他答案,但没有奏效。
这是我在JSON中的数组:
[
{
accountId: "*****",
containerId: "******",
name: "Container23",
},
{
accountId: "**",
containerId: "*",
name: "Container2"
},
{
accountId: "*",
containerId: "*",
name: "Container1",
}
]
其他答案说我必须这样做:
$containers[] = $account['name'];
但是给了我错误的结果,这不是将新值添加到现有的键/值json对象中,而是将它添加到它之上:
"Account2", <------- ??
{
accountId: "1746756959",
Name: "Account2", <---- Here is where i want to add it
name: "Container2"
},
这是我在PHP中的代码:
static public function listAllContainers() {
$containers = array();
foreach (self::listAccounts()->account as $account) {
foreach (self::listAccountsContainers($account["path"]) as $container) {
$containers[] = $container;
//$containers[] = $account['name']; <--- Dont work
}
}
return $containers;
}
答案 0 :(得分:1)
试试这个,
static public function listAllContainers() {
$containers = array();
foreach (self::listAccounts()->account as $accountKey => $account) {
foreach (self::listAccountsContainers($account["path"]) as $container) {
$containers[$account['name']][] = $container;
}
}
return $containers;
}
答案 1 :(得分:0)
这可能不是解决问题的正确方法,但很有趣
$json_data = '[
{
"accountId": "*****",
"containerId": "******",
"name": "Container23"
},
{
"accountId": "**",
"containerId": "*",
"name": "Container2"
},
{
"accountId": "*",
"containerId": "*",
"name": "Container1"
}
]';
快速而肮脏的方式是
$key='newKey';
$val='newVal';
json_decode(str_replace('{','{"'.$key.'":"'.$val.'",',$json_data));