我是Json的新手,我无法使用从mysql查询收集的数据填充json列表。 列表中只填充一个值,它会不断重复而不是显示所有值。 代码是:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('abcd');
$jsonData = 0;
$result = mysql_query("SELECT picname,title,date,time,location,timestamp FROM uploaded_photo_data ORDER BY timestamp DESC ");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
$num = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
$a = $row['location']."/".$row['picname'];
echo $row['timestamp'];
echo $a;
echo $row['picname'];
echo $row['title'];
echo $row['location'];
echo "<br></br>";
$dir = $row['location']."/";
$jsonData = '{';
$x = 0;
$dirHandle = opendir($dir);
while($x!=$num){
$x++;
$jsonData .= '"img'.$x.'":{ "num":"'.$x.'","title":"'.$row['title'].'","src":"'.$a.'", "timestamp":"'.$row['timestamp'].'"},<br></br> ';
}
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData; echo $x;
答案 0 :(得分:4)
您可以使用json_encode
方法将数组编码为JSON。
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
以上示例将输出:
{"a":1,"b":2,"c":3,"d":4,"e":5}
php.net/manual/en/function.json-encode.php
编辑:
也许这适合你:
$jsonData = array();
while ($row = mysql_fetch_assoc($result)) {
$a = $row['location']."/".$row['picname'];
echo $row['timestamp'];
echo $a;
echo $row['picname'];
echo $row['title'];
echo $row['location'];
echo "<br></br>";
$dir = $row['location']."/";
$x = 0;
while($x!=$num){
$x++;
$img = 'img'.$x;
$jsonData[$img] = array(
"num" => $x,
"title" => $row['title'],
"src" => $a,
"timestamp" => $row['timestamp']
);
}
}
print json_encode($jsonData);