如何使用mysqli_fetch_assoc从mysql获取所有行并转换为JSON

时间:2015-12-18 04:42:28

标签: php mysql json

我尝试使用mysqli_fetch_assoc获取mysql表中的所有行。虽然使用这个只获得一行。我需要将结果数组转换为JSON。

$query  =   "SELECT * FROM db_category WHERE publish='1'";
$result =   mysqli_query($c, $query) or die(mysqli_error($c));
$length =   mysqli_num_rows($result);

if($length > 0)
{       
    $var['status']  =   'success';

    while($obj = mysqli_fetch_assoc($result)) 
    {
        $var = array_merge($var, $obj);
        $var1 = json_encode($var);
    }
    echo '{"slider":['.$var1.']}';
}
else
{
    $arr    =   array('status'=>"notfound");
    echo '{"slider":['.json_encode($arr).']}';
}

现在上面代码的输出是,

{"slider":[{"status":"success","category_id":"12","category_name":"Books","publish":"1"}]}

必需的输出是,

{"slider":[{"status":"success","category_id":"1","category_name":"Apparel","publish":"1"},{"status":"success","category_id":"2","category_name":"Footwear","publish":"1"},{"status":"success","category_id":"3","category_name":"Furniture","publish":"1"},{"status":"success","category_id":"4","category_name":"Jewellery","publish":"1"}]}

如何解决这个问题。

1 个答案:

答案 0 :(得分:4)

您可以通过json_encode()功能轻松完成。您还可以使用mysqli_fetch_all()函数将所有数据转换为数组:

$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$jsonData = json_encode(array('slider'=>$data, 'status' => 'success'));

如果您想为每一行添加'status'=>'success',请执行此操作(在json_encode之前)

foreach($data as $key => $dataRow) {
   $data[$key]['status'] = 'success';
}