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'
)
if possible without using any loop? if Yes Then How?
Here is your input array,
$arr= array (
0 => array ( 'sno' => 'q3', 'result' => '15', ),
1 => array ( 'sno' => 'q1', 'result' => '5', ),
2 => array ( 'sno' => 'q2', 'result' => '10', ),
);
Here is one liner code :
$result = array_combine(array_column($arr, 'sno'), array_column($arr, 'result'));
// $result = array_column($arr,'result','sno');
What I am doing is
Here is output:
Array
(
[q3] => 15
[q1] => 5
[q2] => 10
)
Here is working code
Using array_reduce()
you can create new array contain custom key/value from an array.
$newArr = array_reduce($oldArr, function($carry, $item){
$carry[$item["sno"]] = $item["result"];
return $carry;
});
Check code result in demo