0

How to convert a multidimensional array in two arrays in php

This array:

Array
(
    [name] => Array
        (
            [0] => Lighthouse.jpg
            [1] => Penguins.jpg
        )
    [type] => Array
        (
            [0] => image/jpeg
            [1] => image/jpeg
        )
    [tmp_name] => Array
        (
            [0] => C:\wamp\tmp\php525F.tmp
            [1] => C:\wamp\tmp\php5260.tmp
        )
    [error] => Array
        (
            [0] => 0
            [1] => 0
        )
    [size] => Array
        (
            [0] => 561276
            [1] => 777835
        )
)

I want to look like this:

Array
(
    [name] => Lighthouse.jpg
    [type] => image/jpeg
    [tmp_name] => C:\wamp\tmp\php525F.tmp
    [error] => 0
    [size] => 561276
)
Array
(
    [name] => Penguins.jpg
    [type] => image/jpeg
    [tmp_name] => C:\wamp\tmp\php5260.tmp
    [error] => 0
    [size] => 777835
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
user2039290
  • 104
  • 7
  • this might help. then again it might not. http://stackoverflow.com/questions/22456834/php-single-array-to-multidimensional-on-values/22456941#22456941 – n00b Apr 02 '14 at 11:31

4 Answers4

2

Try like

foreach($Arr1 as $key => $value) {
    foreach($value as $key1 => $value1) {
       $Arr2[$key1][$key] = $value1;
    }
}
print_r($Arr2);
GautamD31
  • 28,552
  • 10
  • 64
  • 85
2

Just try with:

$input  = array( /* your input data */ );
$output = array();

foreach ($input as $key => $data) {
  if (!isset($output[$index])) {
    $output[$index] = array();
  }
  foreach ($data as $index => $value) {
    $output[$index][$key] = $value;
  }
}
hsz
  • 148,279
  • 62
  • 259
  • 315
  • `if (!isset($output[$index])) { $output[$index] = array(); }` is unnecessary because PHP does not require the instantiation of parent elements when pushing child elements using square brace syntax. – mickmackusa Sep 08 '22 at 11:31
1
$myArray = array(
    'name' => array( 'Lighthouse.jpg', 'Penguins.jpg' ),
    'type' => array( 'image/jpeg', 'image/jpeg' ),
    'tmp_name' => array( 'C:\wamp\tmp\php525F.tmp', 'C:\wamp\tmp\php5260.tmp' ),
    'error' => array( 0, 0 ),
    'size' => array( 561276, 777835 )
);

$result = array_map(
    function ( $value ) use ( $myArray ) {
        return array_combine( array_keys( $myArray ), $value );
    },
    call_user_func_array( 'array_map', array_merge( array( NULL ), $myArray ) )
);

var_dump($result);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
-1

I didn't understand what you are trying to do here but as answer for your question is

$array1=array($name[0],$type[0],$tmp_name[0],$error[0],size[0]);

$array2=array($name[1],$type[1],$tmp_name[1],$error[1],size[1]);

you can use loop to do that