帮助尝试生成棘手的多维数组格式
我在尝试在 PHP 中构建一个数组时遇到问题,该数组将以我正在寻找的 JSON 格式输出。我将向您展示我想要实现的目标以及到目前为止我已经达到的目标:
[
{"data":[{"x":3,"y":0},{"x":10,"y":0}]},
{"data":[{"x":11,"y":0},{"x":13,"y":0}]},
{"data":[{"x":12,"y":1},{"x":17,"y":1}]}
]
我正在循环数据库结果并尝试构建数组来输出上面的 json,我的 php 看起来像这样(这显然还不正确):
//build the data
$data = array(
array(
'x' => $age_start,
'y' => $ill_type
),
array(
'x' => $age_end,
'y' => $ill_type
)
);
$illnesses[] = $data;
此代码输出以下 json:
[
{
[
[{"x":2,"y":6},{"x":2,"y":6}],
[{"x":2,"y":6},{"x":5,"y":6}],
[{"x":4,"y":6},{"x":4,"y":6}]
]
}
]
任何关于此的指针都很棒!
I'm having trouble trying to build an array in PHP which will output in the JSON format I am looking for. I will show you what I am trying to achieve and where I have got to so far:
[
{"data":[{"x":3,"y":0},{"x":10,"y":0}]},
{"data":[{"x":11,"y":0},{"x":13,"y":0}]},
{"data":[{"x":12,"y":1},{"x":17,"y":1}]}
]
I am looping through db results and trying to build arrays to output the above json, my php looks like this (which is obviously not right yet):
//build the data
$data = array(
array(
'x' => $age_start,
'y' => $ill_type
),
array(
'x' => $age_end,
'y' => $ill_type
)
);
$illnesses[] = $data;
This code outputs the following json:
[
{
[
[{"x":2,"y":6},{"x":2,"y":6}],
[{"x":2,"y":6},{"x":5,"y":6}],
[{"x":4,"y":6},{"x":4,"y":6}]
]
}
]
Any pointers on this would be great!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本上,如果您已经知道所需的 JSON 输出,则只需
json_decode
它以获取它在 PHP 中的表示形式。var_export
函数打印结构以可解析的格式。您也可以使用print_r
或var_dump
来转储结构。上述方法是通用的。只需解码并转储结构即可。然后汇编代码以创建此结构并进行编码。
Basically, if you know your desired JSON output already, you can simply
json_decode
it to get it's representation in PHP. Thevar_export
function prints the structure in parseable format. You can also useprint_r
orvar_dump
to dump the structure though.The above approach is universal. Just decode and dump the structure. Then assemble your code to create this structure and encode.
这样做:
do this:
查看 JSON 字符串,您可以看到:
[
和]
包围),{ 包围)
和}
)data
,它本身就是一个数组x
和 a 的对象组成y
属性重要的是要知道 JSON 对象在 PHP 中由关联数组表示(当
json_encode()
'ing 时,json_decode()
有一个特定的参数来使用stdClass
或 assoc 数组。所以 php 结构如下所示:
Looking at the JSON string, you can see that:
[
and]
){
and}
)data
that is itself an arrayx
and ay
propertyIt is important to know that a JSON object is represented in PHP by an associative array (when
json_encode()
'ing,json_decode()
has a specific parameter to use either astdClass
or an assoc. array).So the php structure looks like this: