Home > database >  Convert nested associative array to single array in php
Convert nested associative array to single array in php

Time:04-22

I have nested array with key & value pair. i want to convert it in single array.

/* This is current array */
Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 2
        )
    [qty] => Array
        (
            [0] => 1
            [1] => 1
        )

    [price] => Array
        (
            [0] => 364.41
            [1] => 300
        )

    [amount] => Array
        (
            [0] => 364.41
            [1] => 300
        )
)
/*Now, I want this type of array*/
Array
(
    [0] => Array
            (
                [id] => 1
                [qty] => 1
                [price] => 364.41
                [amount] => 364.41
            )
    [1] => Array
            (
                [id] => 2
                [qty] => 1
                [price] => 300
                [amount] => 300
            )
)

I have tried array_walk and some other solutions but i could not find any proper solution

Thanks in advance

CodePudding user response:

$mainarray['id'] = Array(1,2,3);
$mainarray['qty'] = Array(1,1,4);
$mainarray['price'] = Array(364.41,300,500);
$mainarray['amount'] = Array(364.41,300,600);
$new = [];     

foreach($mainarray as $key=> $singleArray){
   if(count($singleArray) > 0){
       foreach($singleArray as $childKey=> $value){
                $new[$childKey][$key] = $value;
       }
   };
}` 

CodePudding user response:

Main array is your nested array and Collection is the result you want

        foreach($mainArray["id"] as $key => $value ){
        $collection[$key] = ['id' => $value];
        foreach(array_keys($mainArray) as $arrayKeysOfmainArray){
            if(!array_key_exists($arrayKeysOfmainArray, $collection)){
                $collection[$key][$arrayKeysOfmainArray] = $mainArray[$arrayKeysOfmainArray][$key];
            }
        }
    }

    print_r($collection);
  • Related