Reputation: 435
Basically my issue is, I have a handful of .json files that I need to combine into one. Thankfully that code is already done with and works great. My problem is, now I need to be able to set which files need combined easily without manually rewriting the code each time.
When uploading json files, my server automatically adds the file name to a txt file. All in the same directory for ease of use.
Say I have 3 json files in a single directory, 1.json, 2.json, & 3.json.
It will auto populate a file called 'items.txt' in that directory with all the .json filename in the below format.
'1.json','2.json','3.json'
Here is my php code, mainly focusing on the "$urls = array($items);" part:
$array = explode("\n", file_get_contents('items.txt'));
$items = implode($array);
$urls = array($items);
$jobs = [];
foreach ($urls as $url){
$json = json_decode(file_get_contents($url), true);
array_push($jobs, $json);
}
$unique = array();
foreach ($jobs as $piece) {
$unique = array_merge($unique, $piece);
}
$retour = json_encode($unique);
print_r($retour);
Unfortunately this returns null. But if I change it to this manually:
$urls = array( '1.json','2.json','3.json');
It works as expected.
This is the output if I do "print_r($items);" :
'1.json','2.json','3.json'
So I know the variable is set correctly. How would I be able to output this variable and use it as the url variable above?
I am sorry if this is hard to understand and I will gladly give more detain if it's needed. I hope this is an easy task and I appreciate the help greatly!
Upvotes: 2
Views: 63
Reputation: 120
You could try with a matching regex like
$re = '/\d+\.json/m';
$str = "'10.json','2.json','3.json'";
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
Upvotes: 0
Reputation: 57121
As your current file contents is a CSV with '
as the enclosing quote, you can just use str_getcsv()
$urls = str_getcsv(file_get_contents('items.txt'), ",", "'");
Alternatively you could always store the file list as JSON to maintain consistency with the fact you are using JSON files. So the file would then be
[ "1.json", "2.json", "3.json" ]
and
$urls = json_decode(file_get_contents("a.json"), true));
Upvotes: 2