Jaswinder Posted April 26, 2014 Share Posted April 26, 2014 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 Quote Link to comment https://forums.phpfreaks.com/topic/288047-mutlidimensional-array-to-single-array/ Share on other sites More sharing options...
hakimserwa Posted April 26, 2014 Share Posted April 26, 2014 (edited) use array_merge http://www.php.net/manual/en/function.array-merge.php Edited April 26, 2014 by hakimserwa Quote Link to comment https://forums.phpfreaks.com/topic/288047-mutlidimensional-array-to-single-array/#findComment-1477401 Share on other sites More sharing options...
Solution bsmither Posted April 26, 2014 Solution Share Posted April 26, 2014 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); Quote Link to comment https://forums.phpfreaks.com/topic/288047-mutlidimensional-array-to-single-array/#findComment-1477402 Share on other sites More sharing options...
hakimserwa Posted April 26, 2014 Share Posted April 26, 2014 (edited) 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 April 26, 2014 by hakimserwa Quote Link to comment https://forums.phpfreaks.com/topic/288047-mutlidimensional-array-to-single-array/#findComment-1477414 Share on other sites More sharing options...
Jaswinder Posted April 27, 2014 Author Share Posted April 27, 2014 Thanks @bsmither for nice answer. i works great @hakimserwa. thanks for your efforts too, but your ans is not giving the desired result. Quote Link to comment https://forums.phpfreaks.com/topic/288047-mutlidimensional-array-to-single-array/#findComment-1477420 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.