PHP连接code JSON(2维数组) [英] PHP encode JSON (2 dimensional array)
问题描述
我查询返回到字段的表(message_type&安培;百分比)。
我用PHP连接code JSON数据,这里是我如何做到这一点。
I am querying a table that return to fields(message_type & percentage). I use PHP to encode the json data, here is how i do it
$json = array();
while ($row = odbc_fetch_array($rs)) {
$json[][] = $row;
}
echo json_encode($json);
输出:
[ [ { "message_type" : "bullying",
"percentage" : "60"
} ],
[ { "message_type" : "cheating",
"percentage" : " 14"
} ],
[ { "message_type" : "Stress",
"percentage" : "16"
} ],
[ { "message_type" : "Gang",
"percentage" : "7"
} ]
]
正如你所看到json_en code函数添加大括号,报价和对象键名。
As you can see json_encode function is adding curly braces, quotes and the object key name.
我要的是解析JSON作为唯一的二维数组,这里所需要的输出:
What I want is to parse the json as two dimensional array only, here is the desired output:
[
["bullying", 60],
["harrassment", 9],
["cheating", 14],
["Stress", 16],
["Gang", 7]
]
我也试过手动连接到code,但我不能得到的结果,我需要。
I also tried to encode it manually but I could not get the result I need.
推荐答案
PHP的 json_en code()
使用一定量的魔法,以确定是否给定的矢量是连接codeD作为JSON对象或数组,但简单的规则是这样的:如果数组有连续的,零索引,数字键,它会连接codeD作为数组。任何其他向量(对象或关联数组)将EN codeD作为一个对象。
PHP's json_encode()
uses a certain amount of magic to determine whether a given vector is encoded as a JSON object or an array, but the simple rule is this: If the array has contiguous, zero-indexed, numeric keys, it will be encoded as an array. Any other vector (object or associative array) will be encoded as an object.
由于您使用的是 odbc_fetch_array()
,您的结果行返回的键是列名的关联数组。为了得到你想要的结果,你有3个选项:
Because you are using odbc_fetch_array()
, your result rows are returned as an associative array with the keys being the column names. To get the result you want you have 3 options:
$json[] = array_values($row);
手动构建单独的阵列:
Manually construct the individual arrays:
$json[] = array($row['message_type'], $row['percentage']);
或者可能是最好的选择是使用 odbc_fetch_row()
相反,它会返回索引数组直线距离:
Or probably the best option is to use odbc_fetch_row()
instead, which will return indexed arrays straight away:
while ($row = odbc_fetch_row($rs)) {
$json[] = $row;
}
这篇关于PHP连接code JSON(2维数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!