Suganya Rajasekar Suganya Rajasekar - 3 months ago 20
PHP Question

How to merge one or more nested array values having same keys

I'm little bit confuse in this concept

Actually I'm having an array like this

$arr = array("0"=>array("username"=>"username1"),"1"=>array("username"=>"username2"),"2"=>array("username"=>"username3"),"3"=>array("username"=>"username4"));
echo "<pre>";print_r($arr);
$finalArray = call_user_func_array('array_merge', $arr);
echo "<pre>";print_r($finalArray);


Finally from this I'm getting an array like this

Array
(
[username] => username4
)


But I need all the values like as follows

Array
(
[0] => username1
[1] => username2
[2] => username3
[3] => username4
)


How should I do this?..Could someone please help me..

Thank you,

Answer

Simple solution using array_column function(available since PHP 5.5):

$result = array_column($arr, 'username');