Home > Enterprise >  Array of objects - set keys by object field value
Array of objects - set keys by object field value

Time:01-08

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?

CodePudding user response:

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.

  •  Tags:  
  • Related