Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of objects - set keys by object field value

Tags:

arrays

object

php

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?

like image 335
norr Avatar asked May 23 '26 11:05

norr


1 Answers

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.

like image 88
Syscall Avatar answered May 26 '26 09:05

Syscall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!