The correct way to convert php array -


i have data array like

    $data = [     'name' => [         (int) 0 => '095a108478345cac184f956b1e8dee91a5a89f87bbabd7b3fb4058f577adf.jpg',         (int) 1 => '02059.jpg',         (int) 2 => 'avatar.jpg'     ],     'type' => [         (int) 0 => 'image/jpeg',         (int) 1 => 'image/jpeg',         (int) 2 => 'image/jpeg'     ],     'tmp_name' => [         (int) 0 => 'c:\xampp\tmp\php17aa.tmp',         (int) 1 => 'c:\xampp\tmp\php17ba.tmp',         (int) 2 => 'c:\xampp\tmp\php17bb.tmp'     ],     'error' => [         (int) 0 => (int) 0,         (int) 1 => (int) 0,         (int) 2 => (int) 0     ],     'size' => [         (int) 0 => (int) 80542,         (int) 1 => (int) 6532,         (int) 2 => (int) 6879     ]   ] 

and need convert array this

    $data = [     (int) 0 => [         'name' => '095a108478345cac184f956b1e8dee91a5a89f87bbabd7b3fb4058f577adf.jpg',         'type' => 'image/jpeg',         'tmp_name' => 'c:\xampp\tmp\php17aa.tmp',         'error' => (int) 0,         'size' => (int) 80542     ],     (int) 1 => [         'name' => '02059.jpg',         'type' => 'image/jpeg',         'tmp_name' => 'c:\xampp\tmp\php17ba.tmp',         'error' => (int) 0,         'size' => (int) 6532     ],     (int) 2 => [         'name' => 'avatar.jpg',         'type' => 'image/jpeg',         'tmp_name' => 'c:\xampp\tmp\php17bb.tmp',         'error' => (int) 0,         'size' => (int) 6879     ]    ] 

i'm looking correct way convert first php array second. there of php array functions provided these actions. either possible cakephp hash array management?

yes, can make few foreach loops , create array need, i'm not sure if there more elegant way.

from php 5.5 can use array_column , array_combine it.

$ret = []; $keys = array_keys($data); ($i=0; $i<3; $i++) {     $ret[$i] = array_combine($keys, array_column($data, $i)); } 

where 3 number of elements of name, type, tmp_name, etc.

demo.

the same thing php < 5.5

$ret = []; $keys = array_keys($data); ($i=0; $i<3; $i++) {     $ret[$i] = array_combine($keys, array_map(function($element) use ($i){         return $element[$i];     }, $data)); } 

demo.

and here example, sake of completeness, 2 foreach:

$ret = []; foreach($data $key => $val) {     $i = 0;     foreach ($val $v) {         $ret[$i][$key] = $v;         $i++;     } } 

which way use regardless other implementations.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -