当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何使用mysqli_fetch_assoc从mysql获取所有行并转换为JSON》经验,为你挑选了1个好方法。

我试图从正在使用的mysql表中获取所有行mysqli_fetch_assoc。使用此方法时只会得到一行。我需要将结果数组转换为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> Tᴀʀᴇǫ Mᴀʜᴍᴏᴏ..:

您只需通过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';
}

推荐阅读
郑小蒜9299_941611_G
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有