PHP array. Simple key based partitioning

It is rather a request for quick advice, since it is very difficult for me to believe that there is no native function for this task. 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'm looking for is a new array that uses only "groupname", so it will be equal to:

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

I know that it is very simple to achieve a recursive traversal of the original array, but I was wondering if there is a much simpler way to achieve the final result. I searched the internet and the PHP manual and found nothing

Thank you for reading this question simon

+5
source share
6 answers

If you are using PHP 5.3, you can use array_map [docs] as follows:

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

, (. ).

:

$newArray = array();

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

.

+6

array_column() ( PHP 5.5):

$column = array_column($arr, 'groupname');
+3

array_map:

<?php
$a = array(
    array("id" => "1", "groupname" => "fudge", "etc" => "lorem ipsum"),
    array("id" => "2", "groupname" => "toffee", "etc" => "lorem ipsum"),
    array("id" => "3", "groupname" => "caramel", "etc" => "lorem ipsum")
);

function get_groupname( $arr )
{
    return $arr['groupname'];
}
$b = array_map( 'get_groupname', $a );

var_dump( $a );
var_dump( $b );

http://codepad.org/7kNi8nNm

+1

:

$array = [
    ["id"=>"1","user"=>"Ivan"],
    ["id"=>"2","user"=>"Ivan"],
    ["id"=>"3","user"=>"Elena"]
    ];

$res = [];
$array_separate = function($value, $key) use (&$res){
    foreach($value AS $k=>$v) {
        $res[$k][] = $v;
    }
};

array_walk($array, $array_separate);
print_r($res);

:

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [user] => Array
        (
            [0] => Ivan
            [1] => Ivan
            [2] => Elena
        )

)

http://sandbox.onlinephpfunctions.com/code/3a8f443283836468d8dc232ae8cc8d11827a5355

+1

, PHP , , , . , , :

for($i = 0;$i < count($main_array);$i++){
    $groupname_array[] = $main_array[$i]["groupname"];
}
0
function array_get_keys(&$array, $key) {
    foreach($array as &$value) $value = $value[$key];
}
array_get_keys($array, 'groupname');

function array_get_keys(&$array, $key) {
    $result = Array();
    foreach($array as &$value) $result[] = $value[$key];
    return $result;
}
$new_array = array_get_keys($array, 'groupname');
0

All Articles