【问题标题】:Adding key/value in existing Array - PHP在现有数组中添加键/值 - PHP
【发布时间】:2017-11-01 12:10:45
【问题描述】:

我正在尝试将新的 KEY/VALUE 添加到现有数组中。我遇到了困难,因为我看到了其他答案但没有奏效。

这是我的 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;
    }

编辑:

【问题讨论】:

  • 这甚至不是你想要创建的有效JSON
  • 有效,我没拍完整块
  • json中不能有重复的键
  • 什么意思,重复键在哪里?
  • 啊,我明白了。那么你能为此图像输出编写你的 foreach 代码吗?

标签: php arrays json google-tag-manager


【解决方案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;
    }

【讨论】:

  • 嗨@Mert,这仍然给了我Account['name'] 不在里面的对象之上。
  • 几乎...我更新了我的问题并添加了一张图片以便您查看
【解决方案2】:

这可能不是解决问题的正确方法,但它很有趣

$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));

【讨论】:

    猜你喜欢
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2018-11-27
    • 1970-01-01
    相关资源
    最近更新 更多