我正在努力格式化我的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;
?>
答案 0 :(得分:0)
您只需在每次循环迭代时覆盖$variable
值。这是一个简单的改变。只需确保将在循环中创建的数组放入$variable
中的新数组位置,如下所示:
$variable[] = array(...);
答案 1 :(得分:0)
使用此代码可能会对您有所帮助
while($row = mysql_fetch_array($sql_in))
{
$name=$row['name'];
$id=$row['id'];
$variable[] = array( 'id' => "$id",'name' => "$name" );//use $variable[] instead of $variable
}
echo $json = json_encode($variable);
答案 2 :(得分:0)
像这样
初始化体外的$变量$variable = array();
$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" );
}