创建 JSON 时不会在 php 中生成超过 1 个项目


Creating JSON not making more than 1 item in php

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);
}

IM 获得的输出是

{"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 中,而不仅仅是一个。

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

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

$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);