Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array of objects – set keys by object field value

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading