如何编码多行结果的json?

时间:2019-04-19 09:56:46

标签: php mysql arrays json

我尝试将结果编码为json,但实际上并不起作用。如果查询的结果不止一个,那么它将不起作用。当结果只有一行时,则一切正常。

if (isset($_REQUEST['query'])) {
    $query = $_REQUEST['query'];
    $sql = mysqli_query ($db, "SELECT a, b FROM table WHERE a LIKE '%{$query}%' OR b LIKE '%{$query}%'");
    $array = array();
    while ($row = mysqli_fetch_assoc($sql)) {
        $array[] = array (
            'label' => $row['a'].', '.$row['b'],
            'value' => $row['a'],
        );
    }
    //RETURN JSON ARRAY
    echo json_encode ($array); 
}  

1 个答案:

答案 0 :(得分:0)

尝试此代码

if (isset($_REQUEST['query'])) {
    $query = $_REQUEST['query'];
    $sql = mysqli_query ($db, "SELECT a, b FROM table WHERE a LIKE '%{$query}%' OR b LIKE '%{$query}%'");
    $array = array();
    $i = 0;
    while ($row = mysqli_fetch_assoc($sql)) {
        $array[$i] = array (
            'label' => $row['a'].', '.$row['b'],
            'value' => $row['a'],
        );
        $i++;
    }
    //RETURN JSON ARRAY
    echo json_encode ($array); 
}