Jump to content

Write multiple json files in MySql loop


piearcy

Recommended Posts

I need multiple json files written by their ID number. I call the id separately and also include it in the json file I'm writing. But when I'm writing I'm writing ALL the records in each .json file and not the individual records. 

 

I know I'm just overlooking something but anyone?

 

Here's the code. 

while ($row = $result->fetch_assoc()) {
   $myArray[] = $row;
   $message = json_encode(array($myArray));
   $id = $row['id'];
   $myfile = fopen("message/$id.json", "w") or die("Unable to create file!");
   fwrite($myfile, $message);
   fclose($myfile);
}

Thanks

Link to comment
https://forums.phpfreaks.com/topic/297564-write-multiple-json-files-in-mysql-loop/
Share on other sites

Because you're continuously adding to an array on every iteration. $myArray[] = $row this pushes $row into the array on every iteration. At the end of the loop, $myArray contains the entire contents of your database result.

 

That variable isn't even necessary. Just do:

$message = json_encode(array($row));

the following is equivalent, without the extra $myarray that's causing all the data to be stacked together, to what you are showing -

while ($row = $result->fetch_assoc()) {
    file_put_contents("message/{$row['id']}.json", json_encode($row));
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.