Jump to content

Mutlidimensional array to single array


Jaswinder

Recommended Posts

i want to convert multidimensional array to single array

 

I am having this array

array ( 
0 => array ( 'sno' => 'q3', 'result' => '15', ),
1 => array ( 'sno' => 'q1', 'result' => '5', ), 
2 => array ( 'sno' => 'q2', 'result' => '10', ),
)

i want this resulting array

array ( 'q3' => '15', 'q1' => '5','q2' =>'10' )

i tried foreach, but it gives the values (not an array ) like q3 15 q1 5 q2 10

Link to comment
https://forums.phpfreaks.com/topic/288047-mutlidimensional-array-to-single-array/
Share on other sites

 

Let's start with $a being what we start with, $b being what we want.

$b = array();
foreach ($a as $value)
{
  $b[$value['sno']] = $value['result'];
}
print_r($b);

 

 

that is wrong. if you want to go the loop way it would be

$mult = array ( 
                0 => array ( 'sno' => 'q3', 'result' => '15', ),
                1 => array ( 'sno' => 'q1', 'result' => '5', ), 
                2 => array ( 'sno' => 'q2', 'result' => '10', ),
            );

$marged = array();

foreach($mult as $value){
     foreach($value as $key => $mult_value){
        $marged[$key]= $mult_value; 
      }
}

//$marged array will only have two element becuase all sub array keys are the same. the loop overrides keys of the same name it better you use array index or change the index keys to unique names

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.