【问题标题】:Output JSON array append additional element PHP输出 JSON 数组追加附加元素 PHP
【发布时间】:2017-02-13 23:28:26
【问题描述】:

我很确定我很接近所以希望快速回答​​。

我能够生成这个 JSON:

apps: [
    {
        0: {
            PublisherCount: "7"
    },
        Id: "87",
        AppName: "Productivity, Focus, Habits & Life Success by Audiojoy",
        AppBundle: "productivitymind"
    }
]

但我想达到:

apps: [
    {
        Id: "87",
        AppName: "Productivity, Focus, Habits & Life Success by Audiojoy",
        AppBundle: "productivitymind",
        PublisherCount: "7"
    }
]

这是我的输出循环(我认为问题出在第 5 行,我 array_push 为 PublisherCount 设置了新值。它创建了一个额外的节点,而不是将其添加到末尾。

$temp_array = array();
$i = 0;
while ($row = mysqli_fetch_assoc($publisher_apps)) {
$temp_array[] = $row;
$temp_array[$i][] = fetch_all(get_publisher_count_by_app_id($row['Id']))[0];
$i++;
}

$publisher_apps = $temp_array;

$result = array("apps"=>$publisher_apps);

output_json($result);

谢谢。

【问题讨论】:

  • 嗯,试试$temp_array[$i]['PublisherCount'] = fetch_all(get_publisher_count_by_app_id($row['Id']))[0]['PublisherCount'];(并缩进你的代码)

标签: php arrays json loops


【解决方案1】:

你有这样的行:

['Id' => "87",
 'AppName' => "Productivity, Focus, Habits & Life Success by Audiojoy",
 'AppBundle' => "productivitymind"]

fetch_all(get_publisher_count_by_app_id($row['Id']))[0] 返回一个这样的数组:

['PublisherCount' => 7]

因此,当您将其附加到$temp_array[$i][] 时,整个数组将分配给$temp_array[$i]0 键。

您可以通过多种不同的方式获取 PublisherCount 值。一种方法是使用array_mergeget_publisher_count_by_app_id 的结果与$row 组合,然后将修改后的$row 添加到主数组中。

while ($row = mysqli_fetch_assoc($publisher_apps)) {
    $count = fetch_all(get_publisher_count_by_app_id($row['Id']))[0];
    $temp_array[] = array_merge($row, $count);
}

如果你这样做,$i 应该变得不必要了。

【讨论】:

  • 是的! @Dont'恐慌有效。谢谢你。有道理,我一直得到一个单独的密钥。
【解决方案2】:

改成这样:

$temp_array = array();

while ($row = mysqli_fetch_assoc($publisher_apps)) {
  $row['PublisherCount'] = fetch_all(get_publisher_count_by_app_id($row['Id']))[0]['Pub‌​lisherCount'];
  $temp_array[] = $row;
}

$publisher_apps = $temp_array;

$result = array("apps"=>$publisher_apps);

output_json($result);

【讨论】:

  • 这会导致:apps: [ { Id: "87", AppName: "Productivity, Focus, Habits & Life Success by Audiojoy", AppBundle: "productivitymind", }, { PublisherCount: { PublisherCount: "12" } } ]
  • 我的错,我已经更新了我的答案。请改用更新的代码。然而,在你让它工作之后,你应该考虑使用“fetch_one”或“fetch_first”类型的函数,而不是使用“fetch_all”函数,如果你的代码库中存在这样的函数,以提高性能。
猜你喜欢
  • 2012-05-12
  • 2014-02-24
  • 2022-01-06
  • 2020-04-03
  • 2015-11-12
  • 2021-08-28
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
相关资源
最近更新 更多