我试图从正在使用的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"}]}
如何解决这个问题。
您只需通过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'; }