0

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

3
  • Is the array produced by json_decode()? Commented Sep 7, 2017 at 8:15
  • @axiac no, this data structure is from db. Commented Sep 7, 2017 at 8:17
  • If this data is coming from a database, then what is stopping you from adding a static string as a column in your SELECT clause (aliased as static_text then merely calling array_column($resultSet, 'static_text', 'name')? Commented Sep 23, 2022 at 11:42

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

3 Comments

What if "sample text" is dynamic?
is "sample text" the same for all? put it in a variable, and use that
$multi_arr has 'description' which i can call $single_arr->description to populate "sample text". Sorry about this, should have include this in my question

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.