在php中创建JSON不超过1项

时间:2015-01-30 22:22:37

标签: php arrays json

php中的json文件iam面临的问题是输出只创建一个项目,我需要json中的项目列表。

我的代码:

$jsonarr = array('id' => '', 'source' => $source, 
    'time_date' => $timeunix, 'title' => $titler, 
    'description' => $description, 
    'link' => $linkr,'image' => $imageurl);

for ($x = 0; $x <= count($jsonarr); $x++) {
    echo "The number is: $x <br>";
    echo json_encode($jsonarr);
    $fp = fopen('aaa.json', 'w');
    fwrite($fp, json_encode($jsonarr));
    fclose($fp);
}

输出即将到来

{"id":"","source":"BBC News - Politics","time_date":1422633420,"title":"'Train everyone' for digital world","description":"People everywhere need to adapt to a world being rapidly changed by digital technology, a leading academic says.","link":"http:\/\/www.bbc.co.uk\/news\/uk-wales-politics-31049769#sa-ns_mchannel=rss&amp;ns_source=PublicRSS20-sa","image":"http:\/\/news.bbcimg.co.uk\/media\/images\/80673000\/jpg\/_80673268_glasses_bbc.jpg"}

这是正确的,但我需要将所有项目添加到json而不仅仅是一个。

任何建议都将不胜感激。感谢

1 个答案:

答案 0 :(得分:1)

创建一个字符串并将每个项目附加到字符串并将该字符串写入文件

$results = $db->query("SELECT * FROM table ORDER BY ID DESC");
$jsonString = '';
foreach ($results as $value) {
$id = '"ID":"'.trim($value['ID']).'"';
$artist = '"Artist":"'.trim($value['ArtistName']).'"';
$title = '"AlbumTitle":"'.trim($value['AlbumTitle']).'"';
$items = "\n\t{\n\t\t$id,\n\t\t$artist,\n\t\t$title\n\t},";
$jsonString = $jsonString .$items;
}
$jsonString = rtrim($jsonString,",");
file_put_contents("jsonfile.json", $jsonString);