piearcy Posted July 30, 2015 Share Posted July 30, 2015 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 Quote Link to comment https://forums.phpfreaks.com/topic/297564-write-multiple-json-files-in-mysql-loop/ Share on other sites More sharing options...
scootstah Posted July 31, 2015 Share Posted July 31, 2015 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)); 1 Quote Link to comment https://forums.phpfreaks.com/topic/297564-write-multiple-json-files-in-mysql-loop/#findComment-1517795 Share on other sites More sharing options...
Solution mac_gyver Posted July 31, 2015 Solution Share Posted July 31, 2015 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)); } 1 Quote Link to comment https://forums.phpfreaks.com/topic/297564-write-multiple-json-files-in-mysql-loop/#findComment-1517796 Share on other sites More sharing options...
piearcy Posted July 31, 2015 Author Share Posted July 31, 2015 Thanks guys. Both worked of course but the later was shorter than the former. I knew it would be easy. Appreciate it as always. Quote Link to comment https://forums.phpfreaks.com/topic/297564-write-multiple-json-files-in-mysql-loop/#findComment-1517797 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.