Jump to content

Mutlidimensional array to single array


Jaswinder
Go to solution Solved by bsmither,

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
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
Edited by hakimserwa
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.