我正在尝试将播放列表json文件生成器用于我的Raspberry Pi上的小图片幻灯片项目。
如何使用此格式的php创建json文件?
这是我的PHP代码:
function json_read() {
$link = connect();
$i = 0;
$string = "SELECT * FROM Playlist, Bild WHERE Playlist.Bild_idBild = Bild.idBild";
$result = mysqli_query($link, $string);
while ($row = mysql_fetch_array($result)){
$i[] = array(
'file' => $row['Bild.dateiname'],
'duration' => $row['Playlist.zeit'],
);
$i++;
}
$data = array(
'playlist' => $i
);
echo json_encode($data);
disconnect();
}
它应该如何:
{
"playlist": [
{
"file": "001.jpg",
"duration": 5
},
{
"file": "002.jpg",
"duration": 5
},
{
"file": "003.jpg",
"duration": 10
},
{
"file": "004.jpg",
"duration": 5
},
{
"file": "005.jpg",
"duration": 10
},
{
"file": "006.jpg",
"duration": 5
}
]
}
答案 0 :(得分:1)
需要给出变量语义的名称:
$ i实际上是$ playlist;
function json_read() { $link = connect();
$string = "SELECT * FROM Playlist, Bild WHERE Playlist.Bild_idBild = Bild.idBild";
$result = mysqli_query($link, $string);
// create container for playlist elements
$playlist = array();
while ($row = mysql_fetch_array($result)){
// add new element onto the end container
$playlist[] = array(
'file' => $row['Bild.dateiname'],
'duration' => $row['Playlist.zeit'],
);
}
$data = array(
'playlist' => $playlist
);
echo json_encode($data);
disconnect();
}
答案 1 :(得分:0)
您的代码非常混乱。
您正在递增数组名称。
而不是这段代码:
while ($row = mysql_fetch_array($result)){
$i[] = array(
'file' => $row['Bild.dateiname'],
'duration' => $row['Playlist.zeit'],
);
$i++;
}
使用此:
$arr = array();
while ($row = mysql_fetch_array($result)){
$temp['file'] = $row['Bild.dateiname'];
$temp['duration'] = $row['Playlist.zeit'];
$arr['playlist'][$i] = $temp;
$i++;
}
echo json_encode($arr);