gpt4 book ai didi

php - 在 php 中获取 json 对象而不是 json 数组

转载 作者:搜寻专家 更新时间:2023-11-01 08:26:00 26 4
gpt4 key购买 nike

我希望将 json_encode() 的结果作为一个数组,例如:

[
{
"url":"http://localhost/.....",
"name":"abc"
},
{
"url":"http://localhost/.....",
"name":"xyz"
},
]

但我得到的结果是这样的对象:

{"images":[{"url":"http:\/\/192.168.0.100\/1.JPG","name":"abc"},{"url":"http:\/\/192.168.0.100\/2.JPG","name":"xyz"}]}

php代码:

<?php 

//Importing dbdetails file
require_once 'dbDetails.php';

//connection to database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');

//sql query to fetch all images
$sql = "SELECT * FROM images";

//getting images
$result = mysqli_query($con,$sql);

//response array
$response = array();
$response['images'] = array();

//traversing through all the rows
while($row = mysqli_fetch_array($result)){
$temp = array();
$temp['url']=$row['url'];
$temp['name']=$row['name'];
array_push($response['images'],$temp);

}

//displaying the response
echo json_encode($response);

我试过这样使用 array_values:

 echo json_encode(array_values($response));

但它会导致在 json 字符串之前附加一个 html 代码...

最佳答案

你需要这样做:-

 $response = array();  
//$response['images'] = array(); not needed

//traversing through all the rows
while($row = mysqli_fetch_assoc($result)){ //since you are using name indexes so use _assoc()
$temp = array();
$temp['url']=$row['url'];
$temp['name']=$row['name'];
$response[] =$temp;
}

//displaying the response
echo json_encode($response);

关于php - 在 php 中获取 json 对象而不是 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45052005/

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