PHP重新格式化JSON输出

时间:2014-06-19 19:03:10

标签: php arrays json construct-2

我正在构建2中构建一个hi score board,并且我正在尝试正确地布置字符。

为了做到这一点,我在c2中创建了一个数组,并使用AJAX从我的网络服务器上保存的php脚本中将数据作为JSON字符串返回。然后,这些数据将用于填充数组,然后我将用它来填充我的SpriteFonts。理论上很简单。

这是返回JSON字符串的php文件:

if ($result = $mysqli->query($sql))  {
    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
    $array = array(
        array
        (
            'name' =>  $row['pName'],
            'score' => $row['score']
        ));     
        echo json_encode($array);
    }

    /* free result set */
    $result->free();
    exit();
}

返回以下内容:

[{"name":"developer","score":"56"}]
[{"name":"Terrry","score":"34"}]
[{"name":"Numero_Uno","score":"20"}]
[{"name":"Thomasin :)","score":"18"}]
[{"name":"ThriftyButStillNifty","score":"18"}]
[{"name":"Perfect","score":"17"}]
[{"name":"bah","score":"17"}]
[{"name":"EvilEdna","score":"16"}]
[{"name":"type here","score":"16"}]
[{"name":"Slaine","score":"14"}]

要在C2中使用,字符串必须采用以下格式:

{"c2array":true,
"size":
    [2,2,1],
"data":
[
[["John"],[23]],
[["Terry"],[43]]
]
}

如何从另一个创建一个?

1 个答案:

答案 0 :(得分:1)

我会做这样的事情:

$response = array(
    "c2array" => true,
    "size" => "something",
    "data" => array()
);

while ( $row = $result->fetch_assoc() ) {
    $response['data'][] = array(
        array($row['pName']),
        array($row['score'])
    );
}

echo json_encode($response);