JSON格式化,将命名数组推送到每个集合的现有数组中?

时间:2015-10-27 03:32:08

标签: php arrays json api multidimensional-array

当我从数据库请求多个结果集时,我正在尝试修复JSON API中的问题。基本上我想存储一个命名数组,返回每行的“卡”。我的目标是让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”=> $ values,但是我不能在数组声明的中间执行它,所以我能想到的最好的事情是这样:

// 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
        ),
    )
);

但那当然会给我解析错误。哎呀!有点令人沮丧。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

YES!我想通了。

// 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,
);

这将返回我需要的确切格式。我在思考它。

答案 1 :(得分:1)

按如下方式更改您的代码

<?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}}]}