Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array_values from multidimensional array

Tags:

arrays

php

The array looks like

$arr = array(

  array('a', 'b'),
  array('c', 'd'),
  array('e', 'f'),

)

And I want to get an array with values from the first column, like array('a', 'c', 'e')

I know it can easily be done by iterating the array and store the values in another array, but is there a shorter way, a built-in PHP function or something?

like image 958
thelolcat Avatar asked Mar 14 '12 00:03

thelolcat


People also ask

How to fetch element from array in PHP?

Using array_slice() function: array_slice() returns the sequence of elements from the array as specified by the offset and length parameters. Example: This example illustrates the array_slice() Function to fetch a part of an array by slicing through it, according to the user's choice.

How can I print just the value of an array in PHP?

To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.

How do you flatten an array in PHP?

Flattening a two-dimensional arrayarray_merge(... $twoDimensionalArray); array_merge takes a variable list of arrays as arguments and merges them all into one array. By using the splat operator ( ... ), every element of the two-dimensional array gets passed as an argument to array_merge .


1 Answers

As of PHP 5.5 you can use array_column():

$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'
    )
);

$lastNames = array_column($records, 'last_name', 'id');

print_r($lastNames);

Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)
like image 152
John Conde Avatar answered Oct 13 '22 00:10

John Conde