gpt4 book ai didi

php - 获取自定义格式的json数据

转载 作者:行者123 更新时间:2023-11-30 00:08:44 24 4
gpt4 key购买 nike

我正在努力格式化我的 json 数据。我希望它看起来像这样。我查遍了 stackoverflow 和互联网,但找不到有效的功能。我使用的每个函数都会导致原始 json 数据的格式保持不变。

[
{
"id": 1,
"name": "Kenneth Auchenberg",
"avatar": "http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif",
"type": "contact"
},
{
"id": 2,
"name": "Jon Froda",
"avatar": "http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif",
"type": "contact"
},
{
"id": 3,
"name": "Anders Pollas",
"avatar": "http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif",
"type": "contact"
},

]

但是,它仍然像这样打印:

{"id":"4","name":"Kenneth Auchenberg"}

我已经尝试了网上的所有功能,但没有成功。这是我当前的代码:

<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "root";
$mysql_database = "students";

$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");



$sql_in= mysql_query("SELECT name,id FROM users order by name desc");
while($row = mysql_fetch_array($sql_in))
{
$name=$row['name'];
$id=$row['id'];


$variable = array( 'id' => "$id",
'name' => "$name" );

}
$json = json_encode($variable);

echo $json;
?>

最佳答案

您只是在每次循环迭代时覆盖您的 $variable 值。这是一个简单的改变。只需确保将循环中创建的数组放入 $variable 中的新数组位置,如下所示:

$variable[] = array(...);

关于php - 获取自定义格式的json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24277127/

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