PHP命令json数组格式

时间:2018-01-08 12:17:59

标签: php arrays json sqlsrv

我试图从一个需要采用上述格式的SQL数据库中获取一个json数组

{
"data":[
{
    "name": "foo",
    "age":"bar"
},
{
    "name": "hello",
    "age":"hi"
},
{
    "name": "bar",
    "age":"foo"
},

]
}

下面的代码返回数据,

{
   "0": [
     "name" : "blah",
     "age" : "bleh"
   ],
   "1": [
     "name": "bleh",
     "age" : "blah"
   ],
   "data": []
}

CODE

$_SESSION['userID'] = $userID;
include('USERconfig.php');
$dataArray = array("data"=>array());

$sql = "SELECT name, age FROM dataQue";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
      array_push($dataArray, 
             array("name"=>$row['name'],"age"=>$row['age']));   


}

sqlsrv_free_stmt( $stmt);

header('Content-Type: application/json');
echo json_encode($dataArray);
exit();

如何将所有数据附加到“数据”中?阵列?
我怎样才能摆脱"0","1","2"等?

提前感谢!

2 个答案:

答案 0 :(得分:0)

array_push()会将数据插入到数组之后,我建议您通过回调这个循环中的数组来改变数据的插入方式

$i = 0;
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
    $dataArray['data'][$i]['name'] = $row['name'];
    $dataArray['data'][$i]['age'] = $row['age'];
    $i++;
}

这样,从查询中检索到的所有数据都将添加到日期索引中。通过添加索引($ i)将避免替换先前的寄存器。

答案 1 :(得分:0)

您可以使用:

json_decode($dataArray);

TRUE 添加到json_decode,如:

$dataArray = '{"data":[{"name": "foo","age":"bar"},
                       {"name": "hello","age":"hi"},
                       {"name": "bar","age":"foo"}]}';

print_r(json_decode($dataArray, true));  

结果将是:

Array(
[data] => Array
    (
        [0] => Array
            (
                [name] => foo
                [age] => bar
            )

        [1] => Array
            (
                [name] => hello
                [age] => hi
            )

        [2] => Array
            (
                [name] => bar
                [age] => foo
            )

    ))