Question

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
)
Was it helpful?

Solution 3

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

OTHER TIPS

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

Try like

foreach($Arr1 as $key => $value) {
    foreach($value as $key1 => $value1) {
       $Arr2[$key1][$key] = $value1;
    }
}
print_r($Arr2);

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top