I am using dropzone to get the files uploaded to my Folder. Successfully getting the array of files.
foreach($_FILES as $file) {
print_r($file);
}
Current Output:
Array
(
[name] => Array
(
[0] => Image.PNG
[1] => sadssadsa.PNG
)
[type] => Array
(
[0] => image/png
[1] => image/png
)
[tmp_name] => Array
(
[0] => C:\Users\CH MANAN\AppData\Local\Temp\php48B6.tmp
[1] => C:\Users\CH MANAN\AppData\Local\Temp\php48B7.tmp
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 291647
[1] => 112790
)
)
Expected output:
array
(
[0] => array
(
[name] => Image.PNG
[type] => image/png
[tmp_name] => C:\Users\CH MANAN\AppData\Local\Temp\php48B6.tmp
[error] => 0
[size] => 291647
)
[1] => array
(
[name] => sadssadsa.PNG
[type] => image/png
[tmp_name] => C:\Users\CH MANAN\AppData\Local\Temp\php48B7.tmp
[error] => 0
[size] => 112790
)
)
Tried various loops in the parent loop but not getting the expected results. Someone can help here.
You can use this:
$keys = array_keys($_FILES); // get all the fields name
$res = array_map(null, ...array_values($_FILES)); // group the array by each file
$res = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, $res); // insert the field name to result array
Documentation:
array-keys, array-map and array-combine
Live example: 3v4l
The output for $_FILES
that you see is a standard output for multiple files uploaded. You can iterate over one subarray of $_FILES
(for example name
) and get values from other subarrays under the same key:
foreach ($_FILES['name'] as $key => $value) {
echo $value, $_FILES['error'][$key], $_FILES['tmp_name'][$key]; // etc
}
Look at this example:
$source = [
'name' => [
'test1',
'test2'
],
'type' => [
'jpg',
'png'
]
];
$result = [];
foreach ($source as $key => $subArray) {
foreach ($subArray as $index => $value) {
if (!array_key_exists($index, $result)) {
$result[$index] = [];
}
$result[$index][$key] = $value;
}
}
var_dump($result);
it first looks at the (file) index. if the index does not exist in $result
it will be added. And than it adds the key with value to the corresponding index.
you should work on the basics (manipulating multidimensional arrays et cetera) before advancing. do you have a tutorial or sth else you follow and learn from?
You can loop the array and use array_combine and array_column to transform the array.
foreach($_FILES as $file) {
$keys = array_keys($file);
foreach($file['name'] as $key => $f){
$new[] = array_combine($keys, array_column($file, $key));
}
}
var_dump($new);
See working example:
https://3v4l.org/6lL8J