php 在php中动态构建json数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17332163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:41:43  来源:igfitidea点击:

build json array in php dynamically

phpjson

提问by Mike

I can create simple json objects like this:

我可以像这样创建简单的 json 对象:

$d = array('item' => "$name" ,'rate' => "$rating");

But what if I want to build an array of items and do it dynamically since I am building it from a db query?

但是,如果我想构建一个项目数组并动态执行它,因为我是从 db 查询构建它呢?

Update:

更新:

Let me be more specific I know I have to do:

让我更具体地说明我知道我必须这样做:

$jsonCode = json_encode($d);

which will create a json object with an item and rate field. But I want multiple json objects in a json array when i encode it.

这将创建一个带有项目和费率字段的 json 对象。但是当我对它进行编码时,我想要一个 json 数组中的多个 json 对象。

What I want json wise is something like this:

我想要 json 明智的是这样的:

[{"item":"toy","rating":"baz" },{"item":"bike","rating":"2.3" }, {"item":"juice","rating":"1.3" }]

回答by Felix Kling

But I want multiple json objects in a json array when i encode it.

但是当我对它进行编码时,我想要一个 json 数组中的多个 json 对象。

Then create an array of arraysand pass it to json_encode. The documentation about arraysexplains how to add elements to an array, in the section Creating/modifying with square bracket syntax.

然后创建一个数组数组并将其传递给json_encode. 有关数组文档使用方括号语法创建/修改部分中解释了如何向数组添加元素。

Associative arrays, like the one you already have, will be encoded as objects, "normal" arrays (arrays with consecutive numerical keys) will be encoded as arrays.

关联数组,就像您已有的数组一样,将被编码为对象,“普通”数组(具有连续数字键的数组)将被编码为数组。

Example:

例子:

$d = array();

// This appends a new element to $d, in this case the value is another array
$d[] = array('item' => "$name" ,'rate' => "$rating");

$json = json_encode($d);

回答by Barmar

This will create a multi-dimensional array from your database query, and then encode it as JSON.

这将从您的数据库查询创建一个多维数组,然后将其编码为 JSON。

$d = array();
while ($row = $stmt->fetch_assoc()) {
  $d[] = $row;
}
$json = json_encode($d);

Each $rowwill be an associative array of the data returned from the database. Assigning it to $d[]adds it as an indexed element of that container array.

每个$row都是从数据库返回的数据的关联数组。将它分配给$d[]添加它作为该容器数组的索引元素。

回答by Liam Sorsby

Why not create your array as you just have done but then pass the array through json_encode?

为什么不像刚才那样创建数组,然后将数组传递给它json_encode呢?

If you want a multi-dimensional array, try

如果你想要一个多维数组,试试

$array[] = array("key1" => value1, "key2" => value2);

回答by Techie

What you can do is create a php array dynamically as you want then covert it into a json array as below.

您可以做的是根据需要动态创建一个 php 数组,然后将其转换为 json 数组,如下所示。

$json_array = json_encode($array);

Keep in mind that what you have provided is not a json array

请记住,您提供的不是 json 数组