4

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 i need convert to array like 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 for the correct way to convert the first php array to the second. Is there any of the PHP array functions provided for these actions. Either is possible with CakePHP hash Array management?

Yes, I can make a few foreach loops and create an array what I need, but I'm not sure if there is a more elegant way.

Salines
  • 5,674
  • 3
  • 25
  • 50

1 Answers1

3

From PHP 5.5 you can use array_column and array_combine to do it.

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

Where 3 is the number of elements of name, type, tmp_name, etc.

Demo.

The same thing for PHP < 5.5

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

Demo.

And here an example, for the sake of completeness, with only two foreach:

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

Which by the way I would use regardless to other implementations.

Federkun
  • 36,084
  • 8
  • 78
  • 90