在php中动态构建json数组 [英] build json array in php dynamically

查看:288
本文介绍了在php中动态构建json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can create simple json objects like this:

$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?

更新:

让我更具体一点,我知道我必须做:

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

$jsonCode = json_encode($d);

这将创建一个带有item和rate字段的json对象.但是我在对json数组进行编码时希望有多个json对象.

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明智的是这样的

What I want json wise is something like this:

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

推荐答案

但是我在对json数组进行编码时想要多个json对象.

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

然后创建一个数组数组,并将其传递给json_encode. 关于数组的文档使用方括号语法创建/修改.

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

与您已经拥有的数组一样,关联数组将被编码为对象,普通"数组(具有连续数字键的数组)将被编码为数组.

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.

示例:

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

这篇关于在php中动态构建json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆