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 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 use array_merge http://www.php.net/manual/en/function.array-merge.php Link to comment https://forums.phpfreaks.com/topic/288047-mutlidimensional-array-to-single-array/#findComment-1477401 Share on other sites More sharing options...
bsmither Posted April 26, 2014 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); 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 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 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. 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
Archived
This topic is now archived and is closed to further replies.