转换数组的结构


Converting the structure of an array

我有以下数组:

Array ( 
   [0] => Information.pdf
   [1] => Presentation.pdf
   [2] => Brochure.pdf
) 

我想使用 PHP 将其转换为以下格式的嵌套数组,以使其与 CakePHP 2.1.1 电子邮件类兼容:

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  
   ) 
)

关于如何做到这一点的任何想法?"mimetype"可以硬编码。

$nested = array();
foreach($flat as $filename) {
    $nested[$filename] = array(
        'file' => '/files/'.$filename,
        'mimetype' => 'application/pdf'
    );
};

对于 mimetype 猜测,fileinfo 扩展名将是一个不错的选择。

使用 foreach 遍历数组项并使用 mime_content_type() 获取 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)
    );
};
$newArr = array();
foreach($arr as $val) {
    $newArr[$val] = array(
        "file"      =>  "/files/".$val,
        "mimetype"  =>  "application/pdf"
    );
}
<?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]);
}
?>