当我从数据库请求多个结果集时,我正在尝试修复JSON API中的一个问题。基本上,我想存储一个命名数组,"card"用于返回的每一行。我的目标是让JSON看起来像这样:
{
"results": [
{
"card": {
"property": "value",
"property": "value",
"property": "value"
}
},
{
"card": {
"property": "value",
"property": "value",
"property": "value"
}
}
]
}
但相反,它看起来是这样的:
{
"results": [
{
"card": [
{
"property": "value",
"property": "value",
"property": "value"
},
{
"property": "value",
"property": "value",
"property": "value"
}
]
}
]
}
下面你可以找到我的代码:
// Prepare Stored Procedure Call
$dbConn = new ConnDB();
$dbConn->query("CALL " . $this->proc);
//Get Result$$$
$row = $dbConn->resultset();
foreach ($row as $key => $value) {
$this->valueArray[$key] = $value;
}
$this->data = array(
"results" => array(
array(
$this->type => $this->valueArray
),
)
);
我基本上需要为每一个$行构建一个命名数组,"card"=>$值,但我不能在数组声明的中间进行,所以我能想到的最好的事情是:
// Prepare Stored Procedure Call
$dbConn = new ConnDB();
$dbConn->query("CALL " . $this->proc);
//Get Result$$$
$row = $dbConn->resultset();
$jsonArray = array();
foreach ($row as $key => $value) {
array_push($jsonArray, $this->type => $this->valueArray[$key] = $value)
}
$this->data = array(
"results" => array(
array(
$jsonArray
),
)
);
但这当然会给我带来解析错误。啊!有点令人沮丧。
有什么想法吗?
是!我想明白了。
// Prepare Stored Procedure Call
$dbConn = new ConnDB();
$dbConn->query("CALL " . $this->proc);
//Get Result$$$
$row = $dbConn->resultset();
$jsonArray = array();
foreach ($row as $key => $value) {
array_push($jsonArray, array("card" => $value));
}
$this->data = array(
"results" => $jsonArray,
);
这将返回我需要的确切格式。我想得太多了。
按以下更改代码
<?php
$data = array();
$json_array = array();
$test_array = array(1,2,3,4,5,6,7,8,9,10);
foreach($test_array as $t){
$json_array[]['card'] = array('property' => $t);
}
$data['results'] = $json_array;
echo json_encode($data);
?>
结果
{"results":[{"card":{"property":1}},{"card":{"property":2}},{"card":{"property":3}},{"card":{"property":4}},{"card":{"property":5}},{"card":{"property":6}},{"card":{"property":7}},{"card":{"property":8}},{"card":{"property":9}},{"card":{"property":10}}]}