Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific element from each sub array

Tags:

arrays

php

I have a common pattern which Im sure there must be a built-in array function in PHP to handle but just can't see it.

I have multiple arrays such as the following:

$testArray = array (
    'subArray1' => array(
        'key1' => "Sub array 1 value 1",
        'key2' => "Sub array 1 value 1"
    ),
    'subArray2' => array(
        'key1' => "Sub array 2 value 1",
        'key2' => "Sub array 2 value 2"
    )
);

I need to get the key1 values from each subArray, of which there can be any number.

I always end up just looping over each array to get the required values, but I'm sure there must be an easier, more efficient way to handle this.

I am currently using the following simple foreach to parse the arrays:

$preparedSubs = array();

foreach($testArray as $subArray) {
    $preparedSubs[] = $subArray['key1'];
}

It's as short as I can make it, but as I said I'm sure there is a PHP construct that would handle this better.

like image 860
Marty Wallace Avatar asked Apr 22 '12 13:04

Marty Wallace


People also ask

How do I access Subarray?

slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Basically, slice lets you select a subarray from an array.

Can Subarray be a single element?

Show activity on this post. Answer is yes.

How do you select a sub array in Python?

We can also select a sub array from Numpy Array using [] operator i.e. It will return a sub array from original array with elements from index first to last – 1.


2 Answers

Before PHP 5.5, this would be the most efficient solution:

$key = 'key1';

$output = array_map(function($item) use ($key) {
    return $item[$key];
}, $testArray);

As of PHP 5.5, there is now an array_column function for this (see COil's answer).

like image 78
cmbuckley Avatar answered Oct 08 '22 16:10

cmbuckley


As of PHP 5.5 you can use the array_column() function:

$key = 'key1';

$testArray = array (
    'subArray1' => array(
        'key1' => "Sub array 1 value 1",
        'key2' => "Sub array 1 value 2"
    ),
    'subArray2' => array(
        'key1' => "Sub array 2 value 1",
        'key2' => "Sub array 2 value 2"
    )
);

$output = array_column($testArray, $key);
var_dump($output);

Will output:

array(2) {
  [0]=>
  string(19) "Sub array 1 value 1"
  [1]=>
  string(19) "Sub array 2 value 1"
}

The only difference with the accepted answer is that you lose the original key name, but I think this is not a problem in your case.

like image 27
COil Avatar answered Oct 08 '22 15:10

COil