April 30, 2012

Converting the structure of an array

Question by Joseph

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.

Answer by ThiefMaster

$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.

Answer by Starx

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!