11

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;
}
1

1 Answer 1

15

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
        )

)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Unfortunately I don't have array_column() available on my ded server.
@Thom You could do a little workaround with array_combine() and array_map(), like this: $result = array_combine( array_map(function($v)use($column){ return $v[$column] }, $a), $a); OR you can use array_column() for under php 5.5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.