Say for example you just queried a database and you recieved this 2D array.
$results = array(
array('id' => 1, 'name' => 'red' , 'spin' => 1),
array('id' => 2, 'name' => 'green', 'spin' => -1),
array('id' => 3, 'name' => 'blue' , 'spin' => .5)
);
I often find myself writing loops like this.
foreach($results as $result)
$names[] = $result['name'];
My questions is does there exist a way to get this array $names without using a loop? Using callback functions count as using a loop.
Here is a more generic example of getting every field.
foreach($results as $result)
foreach($result as $key => $value)
$fields[$key][] = $value;
PHP: Extract a slice of the arrayThe array_slice() function is used to extract a slice of an array. The array_slice() function returns the sequence of elements from the array array as specified by the starting_position and slice_length parameters. Array name. Specifies the beginning position of the slice in the array.
PHP | array_flip() Function This built-in function of PHP is used to exchange elements within an array, i.e., exchange all keys with their associated values in an array and vice-versa. We must remember that the values of the array need to be valid keys, i.e. they need to be either integer or string.
A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.
As of June 20th in PHP-5.5 there is a new function array_column
For example:
$records = array( array( 'id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe' ), array( 'id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith' ), array( 'id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones' ), array( 'id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Doe' ) ); $firstNames = array_column($records, 'first_name'); print_r($firstNames);
Will return
Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )
There are even more examples in the above mentioned link.
I voted @Devon's response up because there really isn't a way to do what you're asking with a built-in function. The best you can do is write your own:
function array_column($array, $column)
{
$ret = array();
foreach ($array as $row) $ret[] = $row[$column];
return $ret;
}
Starting PHP 5.3, you can use this pretty call with lambda function:
$names = array_map(function ($v){ return $v['name']; }, $results);
This will return array sliced by 'name' dimension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With