3

I have associative array of objects. I want to set keys in that array by object field value. All questions I looked at were about grouping, but in my case these values are always unique.

What I have:

<?php

$demo = [
    (object) ['key' => 'a', 'xxx' => 'xxx'],
    (object) ['key' => 'b', 'xxx' => 'xxx'],
    (object) ['key' => 'c', 'xxx' => 'xxx']
];

$result = [];
foreach ($demo as $item) {
    $result[$item->key] = $item;
}

die(print_r($result));

Result:

Array
(
    [a] => stdClass Object
        (
            [key] => a
            [xxx] => xxx
        )

    [b] => stdClass Object
        (
            [key] => b
            [xxx] => xxx
        )

    [c] => stdClass Object
        (
            [key] => c
            [xxx] => xxx
        )
)

But is there better way, without loop? What would be shortest solution, some one-liner?

1 Answer 1

4

You could use array_combine() and array_column().

array_column() to get the keys, and array_combine() to build the array using the extracted keys and objects as values.

$demo = [
    (object) ['key' => 'a', 'xxx' => 'xxx'],
    (object) ['key' => 'b', 'xxx' => 'xxx'],
    (object) ['key' => 'c', 'xxx' => 'xxx']
];

print_r(array_combine(array_column($demo, 'key'), $demo));

Output:

Array
(
    [a] => stdClass Object
        (
            [key] => a
            [xxx] => xxx
        )

    [b] => stdClass Object
        (
            [key] => b
            [xxx] => xxx
        )

    [c] => stdClass Object
        (
            [key] => c
            [xxx] => xxx
        )

)

See a working demo.

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

2 Comments

I don't think this works if the objects do not implement ArrayAccess
This works with custom objects with public properties : demo 3v4l.org/FodFh

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.