I have multiple files that contain json data that looks like this:
1.json:
[{ "id": 2100059, "email": "", "company": "acme", "job_title": "", "first_name": "Jane", "last_name": "Doe" }, { "id": 2199991, "email": "", "company": "Widgets Inc", "job_title": "", "first_name": "John", "last_name": "Doe" }]
2.json:
[{ "id": 123456, "email": "", "company": "acme", "job_title": "", "first_name": "GI Jame", "last_name": "Adf" }, { "id": 000001, "email": "", "company": "Widgets Inc", "job_title": "", "first_name": "bob", "last_name": "billy" }]
How can I combine these two lists so that it's just one string, with one set of []?
So far, I'm writing the logic read in the contents of each file into separate strings. But then I'm thinking I should: 1. json_decode() each string to treat it like an object
Not sure how to append to the object though. any tips would be appreciated.
EDIT 1
I decided to read each file contents into an array, and then try the tips suggested below to use array_merge. when i do a print_r on my array, it looks like this: (bogus data, but you should get the idea)
Array ( [0] => [{"id":2100059,"email":"","company":""},{"id":2129527,"email":"","company":""},{"id":2134804,"email":"","company":""},{"id":2148239,"email":"","company":""}] [1] => [{"id":2100059,"email":"","company":""},{"id":2129527,"email":"","company":""},{"id":2134804,"email":"","company":""},{"id":2148239,"email":"","company":""}][2] => [{"id":2100059,"email":"","company":""},{"id":2129527,"email":"","company":""},{"id":2134804,"email":"","company":""},{"id":2148239,"email":"","company":""} [3] =>[{"id":2100059,"email":"","company":""},{"id":2129527,"email":"","company":""},{"id":2134804,"email":"","company":""},{"id":2148239,"email":"","company":""}]
)
And then this is the logic I have that tries to combine all this into one json string:
print_r($allpages);
$finaljsonstring =‘’;
foreach ($allpages as $item)
{
$finaljsonstring = $finaljsonstring + json_encode(array_merge(json_decode($item)));
}
echo $finaljsonstring;
But something is going wrong. (I’m calling this as ajax so it’s hard to debug) but when i console.log the results from the ajax call, nothing is returned. Ultimately, what I need to return to the front end is a single array of json strings like this:
[{}, {},{}]
#php #json #ajax