Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert value from specific multidimensional array key into key in new array with original arrays as value

Basically I just would like to know if there is a built-in way of doing this, that might be faster, like maybe with an array_map callback or something:

function array_rekey($a, $column)
{
    $array = array();
    foreach($a as $keys) $array[$keys[$column]] = $keys;
    return $array;
}
like image 724
Works for a Living Avatar asked May 06 '15 03:05

Works for a Living


People also ask

How do I change the value of a key in an array?

Change Array Key using JSON encode/decode It's short but be careful while using it. Use only to change key when you're sure that your array doesn't contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.

How do you get a specific value from an array?

Answer: Use the Array Key or Index If you want to access an individual value form an indexed, associative or multidimensional array you can either do it through using the array index or key.

What is array_keys () used for?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.


1 Answers

This should work for you:

Just pass NULL as second argument to array_column() to get the full array back as values and use $column as third argument for the keys.

$result = array_column($arr, NULL, $column);

example input/output:

$arr = [
        ["a" => 1, "b" => 2, "c" => 3],
        ["a" => 4, "b" => 5, "c" => 6],
        ["a" => 7, "b" => 8, "c" => 9],
    ];

$column = "b";
$result = array_column($arr, NULL, $column);
print_r($result);

output:

Array
(
    [2] => Array
        (
            [a] => 1
            [b] => 2
            [c] => 3
        )

    [5] => Array
        (
            [a] => 4
            [b] => 5
            [c] => 6
        )

    [8] => Array
        (
            [a] => 7
            [b] => 8
            [c] => 9
        )

)
like image 179
Rizier123 Avatar answered Oct 13 '22 01:10

Rizier123