【发布时间】:2020-03-15 16:41:22
【问题描述】:
我有这段代码用于将 json 写入文件
<?php
require_once 'vendor/autoload.php';
$faker = Faker\Factory::create();
function getAge($start = 18, $end = 100, $repeat = 20){
$result = null;
static $ages = array();
if ( empty($ages) ) {
for ($i= $start; $i <= $end; $i++) {
for($j = 0; $j < $repeat; $j++)
$ages[] = $i;
}
}
$index = rand(0, count($ages));
$result = $ages[ $index ];
unset($ages[ $index ]);
$ages = array_values($ages);
return $result;
}
$superstars = array("Adam Cole","Finn Balor","Pete Dunne","Jordan Devlin","Noam Dar");
$fan_favourite_superstar_name = $superstars[ mt_rand( 0, count($superstars) -1 ) ];
$cities = array("London","Manchester","Leeds","Bristol");
$fan_location = $cities[ mt_rand( 0, count($cities) -1 ) ];
$the_models = array("Iphone","Nokia","Huawei","Samsung");
$fan_phone_model = $the_models[ mt_rand( 0, count($the_models) -1 ) ];
for ($x = 1; $x <= 100; $x++) {
echo $x;
$array = Array (
"$x" => Array (
"id" => uniqid(),
"fan_favourite_superstar_name" => $fan_favourite_superstar_name,
"fan_location" => $fan_location,
"fan_phone_model" => $fan_phone_model,
"fan_name" => $faker->name,
"fan_age" => getAge(),
"fan_comments" => $faker->text,
"fan_picture" => rand(1,500),
"last_updated" => time() + rand(1,1000),
)
);
// encode array to json
$json = json_encode(array('fans' => $array));
//write json to file
if (file_put_contents("data.json", $json))
echo "JSON file created successfully..."."<br/>";
else
echo "Oops! Error creating json file...";
}
?>
当我运行时,只写第一行。为什么其他行不写了?
【问题讨论】:
-
不确定是否在循环中正确设置了数组中的值,试试
$array[$x] = Array ( "id" => uniqid(), -
您每次都在覆盖文件。见this。
-
@El_Vanja 你是对的,这是缺少
if ( file_put_contents('data.json', $json.PHP_EOL , FILE_APPEND | LOCK_EX)) -
如果您将单独的 JSON 编码字符串附加到文件中,则它不再是 JSON 文件。
-
@NigelRen 是的。我想要我的 json
{"fans":[{"id":"5e6e601da9a44","fan_favourite_superstar_name":"Pete Dunne","fan_location":"Bristol","fan_gender":"Female","fan_phone_model":"Nokia","fan_name":"Shemar Oberbrunner","fan_age":55,"fan_comments":"Et ","fan_picture":189,"last_updated":1584292832},{"id":"5e6e601da9cc1","fan_favourite_superstar_name":"Pete Dunne","fan_location":"Bristol","fan_gender":"Female","fan_phone_model":"Nokia","fan_name":"Gertrude Wiegand","fan_age":45,"fan_comments":"Repudiandae ","fan_picture":346,"last_updated":1584292326}]}格式
标签: php