I receive a json of data, which can contain one or more attachments, all of them are received in base64. I give you an example:
{
"id": 1,
"data": {
"nombre": "Nombre",
"file1": "Mhuc2dvCg==",
"file2": "Yhj4dysYn==",
"file3": "Jusj6Hism==",
"file4": "Rhsy7Yhah==",
...
}
}
I have managed to upload a file, but I don't know how to make it identify each one that arrives in the json. That is, if I do:
$adjunto1 = isset($input['data']['file1']) ? $input['data']['file1'] : '';
And after this I call the function subirFichero($adjunto1);
everything works correctly. But how do I recognize all the files that arrive in the json, that is, check that if it starts with "file" it is an attached file and insert them?
You have two solutions depending on whether or not you can/want to improve the structure of the JSON data sent:
Keeping the JSON format
You can iterate through each element using a
foreach
and check that the index is notnombre
:The output obtained is:
Optimizing the JSON format
Normally, the content of the JSON facilitates its analysis by the application that receives the data, therefore the ideal is to adjust its content to a property that unambiguously enumerates the files:
So the PHP code is greatly simplified:
The output obtained is (same as before):
You could do it using an array and a foreach like so:
Or if you want, you can upload the files inside the loop like so: