Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array. Simple split based on key

Tags:

arrays

php

split

This is more a request for a quick piece of advice as, I find it very hard to believe there isn't a native function for the task at hand. Consider the following:

array => 
(0) => array("id" => "1", "groupname" => "fudge", "etc" => "lorem ipsum"),
(1) => array("id" => "2", "groupname" => "toffee", "etc" => "lorem ipsum"),
(2) => array("id" => "3", "groupname" => "caramel", "etc" => "lorem ipsum")
)

What I am looking to get is a new array which uses only "groupname" so would equal:

array =>
(0) => "fudge",
(1) => "toffee",
(2) => "caramel"
)

I know this is very simple to achieve recursively going through the original array, but I was wondering if there is a much simpler way to achieve the end result. I've looked around the internet and on the PHP manual and can't find anything

Thank you kindly for reading this question Simon

like image 805
Simon Avatar asked Nov 02 '11 17:11

Simon


2 Answers

There is a native array_column() function exactly for this (since PHP 5.5):

$column = array_column($arr, 'groupname');
like image 145
flori Avatar answered Sep 22 '22 17:09

flori


If you are using PHP 5.3, you can use array_map [docs] like this:

$newArray = array_map(function($value) {
    return $value['groupname'];
}, $array);

Otherwise create a normal function an pass its name (see the documentation).

Another solution is to just iterate over the array:

$newArray = array();

foreach($array as $value) {
    $newArray[] = $value['groupname'];
}

You definitely don't have to use recursion.

like image 32
Felix Kling Avatar answered Sep 23 '22 17:09

Felix Kling