简体   繁体   English

返回json_object作为数组的正确方法

[英]correct way to return a json_object as an array

I have an array populated using an sql statement in the following manner: 我有一个以以下方式使用sql语句填充的数组:

$index = 0;

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
    $bookname[$index] = ($row['Bookname']);
    $subjectname[$index] = ($row['SubjectName']);
    $index++;
}

When I go to echo json encode the Arrays I get a blank [] when I know it has been populated which is really weird. 当我回声对数组进行json编码时,当我知道它已经被填充时,我得到了一个空白[],这确实很奇怪。 Am I doing anything wrong in my context 我在上下文中做错了什么吗

echo json_encode($Bookname,$SubjectName);

You can use json_encode as like that: 您可以像这样使用json_encode

<?php
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
    $data[$index]['bookname'] = $row['Bookname'];
    $data[$index]['subjectname'] = $row['SubjectName'];
    $index++;
}
json_encode($data); // encode your array
?>

Try following: 请尝试以下操作:

       $index = 0;
       $data = array();
       while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
      {
        $data['Bookname'][$index] = $row['Bookname'] 
        $data['SubjectName'][$index] = $row['SubjectName'];
        $index++;

       }
       echo json_encode($data);

You have passed two parameter while calling json_encode function. 您在调用json_encode函数时传递了两个参数。 You batter combine two array in one. 您将两个数组合并为一个。 Then call the json_encode function like json_encode($combinedArray) 然后调用json_encode函数,例如json_encode($combinedArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM