Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting php array of arrays into single array

Tags:

arrays

php

I have an array whose values are all arrays of a specific format that looks like this:

Array (     [0] => Array            (                [username] => John            )         [1] => Array            (                [username] => Joe            )     [2] => Array            (                [username] => Jake            ) ) 

and I would like to have this:

Array (     [0] => John        [1] => Joe     [2] => Jake ) 

I can do this manually with a loop but is there a better way? If not, is it possible to do this for an array of objects that have a common attribute?

like image 358
jhchen Avatar asked Feb 18 '10 14:02

jhchen


People also ask

How do I make multiple arrays into one array?

Using concat method The concat method will merge two or more arrays into a single array and return a new array. In the code above, we have merged three arrays into an empty array. This will result in merging multiple arrays into a new array.

How do you merge arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How can I append an array to another array in PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );


2 Answers

Since PHP 5.5.0 there is a built-in function array_column which does exactly this.

like image 164
Peter Taylor Avatar answered Sep 20 '22 05:09

Peter Taylor


why complicate things?

foreach($array as $k=>$v) {     $new[$k] = $v['username']; } 
like image 45
SilentGhost Avatar answered Sep 21 '22 05:09

SilentGhost