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?