Skip to content
Advertisement

Create associative array with a static string for values and keys from an array column

I have an array object like this:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => sam
        )

    [1] => stdClass Object
        (
            [id] => 2
            [name] => tim
        )

    [2] => stdClass Object
        (
            [id] => 3
            [name] => nic
        )

)

And I want to have this:

Array
(
    [sam] => sample text
    [tim] => sample text
    [nic] => sample text
)

My current approach:

$arr = array();

foreach($multi_arr as $single_arr) {
    $arr[$single_arr->name] = "sample text";
}

Is there a cleaner/better approach than this? Thanks

Advertisement

Answer

You can use array_map to get all the keys, then use array_fill_keys to populate the final array.

$arr = array_fill_keys(array_map(function($e) {
    return $e->name;
}, $multi_arr), "sample text");

If sample text is part of the stdClass object:

$arr = array_merge(...array_map(function($e) {
    return [$e->name => $e->description];
}, $multi_arr));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement