1

how to convert associative array to different array?

This is my array

$array=Array ( 
services => Array ( [0] => 6, [1] => 1, [2] => 3 ),
subservices => Array ( [0] => 'No data',[1] => 2 ,[2] => 'No data' ),
price=> Array ( [0] => 124, [1] => 789, [2] => 895 ),
);

and i want convert to

 Array (   
    [0] => Array ( [services] => 6, [subservices] => 'No data', [price] => 124 )  
    [1] => Array ( [services] => 1, [subservices] => 2, [price] => 789 )  
    [2] => Array ( [services] => 3, [subservices] => 'No data', [price] => 895 ) 
     )

How to do?

1
  • What have you tried ? Show your code Commented Oct 6, 2018 at 6:16

2 Answers 2

1
$outArray=array();
for($i=0;$i<count($sourceArray['services']);$i++)
{
    $outArray[]=array('services'=>$sourceArray['services'][$i],'subservices'=>$sourceArray['subservices'][$i],'price'=>$sourceArray['price'][$i]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks man, its working. Here this type of array function exists?
0

Here is a dynamic approach. This will also allow for additional values in your sub arrays.

Hope it helps:

$array = array (
'services' => Array ( '0' => 6, '1' => 1, '2' => 3),
'subservices' => Array ( '0' => 'No data', '1' => 2, '2' => 'No data'),
'price' => Array ( '0' => 124, '1' => 789, '2' => 895)
);

//Get array keys.
$keys = array_keys($array);

//Iterate through the array.
for($i = 0; $i < count($array); $i++){
  //Iterate through each subarray.
  for($j = 0; $j < count($array[$keys[$i]]); $j++){

    //Here we are checking to see if you have more data per element than your initial key count.
    if($keys[$j]){

      $index = $keys[$j];

    } else {

      $index = $j;

    }

    //Append results to the output array.
    $results[$i][$index] = $array[$keys[$i]][$j];

  }

}


echo '<pre>';
print_r($results);
echo '</pre>';

This will output:

Array
(
    [0] => Array
        (
            [services] => 6
            [subservices] => 1
            [price] => 3
        )

    [1] => Array
        (
            [services] => No data
            [subservices] => 2
            [price] => No data
        )

    [2] => Array
        (
            [services] => 124
            [subservices] => 789
            [price] => 895
        )

)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.