gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:03:02 24 4
gpt4 key购买 nike

我已经尝试从使用 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":"家具","publish":"1"},{"status":"成功","category_id":"4","category_name":"珠宝","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';
}

关于php - 如何使用 mysqli_fetch_assoc 从 mysql 中获取所有行并转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34348657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com