I have the following array:
Array (
[0] => Information.pdf
[1] => Presentation.pdf
[2] => Brochure.pdf
)
I want to convert it into a nested array in the following format using PHP to make it compatible with the CakePHP 2.1.1 email class:
Array (
[Information.pdf] => Array (
[file] => /files/Information.pdf
[mimetype] => application/pdf
)
[Presentation.pdf] => Array (
[file] => /files/Presentation.pdf
[mimetype] => application/pdf
)
[Brochure.pdf] => Array (
[file] => /files/Brochure.pdf
[mimetype] => application/pdf
)
)
Any ideas on how to do this? The "mimetype" can be hardcoded.
$nested = array();
foreach($flat as $filename) {
$nested[$filename] = array(
'file' => '/files/'.$filename,
'mimetype' => 'application/pdf'
);
};
For mimetype guessing, the fileinfo extension would be a good choice.
$newArr = array();
foreach($arr as $val) {
$newArr[$val] = array(
"file" => "/files/".$val,
"mimetype" => "application/pdf"
);
}
Use a foreach
to iterate through the array items and use mime_content_type()
to get the mimetype.
$temp = array(); //A temporary array to store new array
foreach($array as $filename) { //Supposing $array is your original array
$file = '/files/'.$filename;
$temp[$filename] = array(
'file' => $file,
'mimetype' => mime_content_type($file)
);
};
<?php
$arr = array('Information.pdf','Presentation.pdf','Brochure.pdf'); //current array
$new_arr = array();
foreach($arr as $key=>$value){
$val = explode(".",$value);
$new_arr[$value]=array('file'=>"/files/".$value,'mimetype'=>"application/".$value[1]);
}
?>