3

I got multidimensional arrays i want it to break into multi array in one variable

Array
(
    [name] => Array
        (
            [0] => John Davis
            [1] => Marie J
        )

    [work] => Array
        (
            [0] => employee
            [1] => none
        )

    [address] => Array
        (
            [0] => street 1
            [1] => street 2
        )

)

I want output to :

$array1 = array("name" => "John Davis", "work" => "employee", "address" => "street 1");
$array2 = array("name" => "Marie J", "work" => "none", "address" => "street 2");

and how to generate dynamically if values keys more than 2

thanks alot

haidarvm
  • 611
  • 8
  • 17
  • check this out: https://stackoverflow.com/questions/46469966/php-split-multidimensional-array-by-key-value – Sofyan Thayf Feb 09 '18 at 12:55
  • Similar Link https://stackoverflow.com/questions/6785355/convert-multidimensional-array-into-single-array#6785366 – Vishnu Bhadoriya Feb 09 '18 at 12:58
  • 1
    Possible duplicate of [PHP - Split Multidimensional Array by key/value](https://stackoverflow.com/questions/46469966/php-split-multidimensional-array-by-key-value) – Adeel Feb 09 '18 at 13:05
  • no guys please make sure i need the array key to be exact name, work, address, not digit 0,1,2,3 – haidarvm Feb 09 '18 at 13:12

2 Answers2

3

Please try below code get output:

$newArray = [];
foreach ($outerArray as $outerkey => $outerArr) {
    foreach ($outerArr as $key => $innerArr) {
        $newArray[$key][$outerkey] = $innerArr;
    }
}

print_r($newArray);
Pratik Gadoya
  • 1,420
  • 1
  • 16
  • 27
1

Functional solution

// make array of keys
$keys = array_keys($arr);
// combine it with data sets 
$res = array_map(function (...$x) use($keys) 
       { return array_combine($keys, $x); },
       ...array_values($arr));

demo

splash58
  • 26,043
  • 3
  • 22
  • 34