John Davidson

php - Array of objects - set keys by object field value

0 comments
Message:


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?



My Answer:
php
$objects = [
(object) ['id' => 1, 'name' => 'John'],
(object) ['id' => 2, 'name' => 'Jane'],
(object) ['id' => 3, 'name' => 'Alice']
];


_What I want:_

php
$objectsByKey = [
1 => (object) ['id' => 1, 'name' => 'John'],
2 => (object) ['id' => 2, 'name' => 'Jane'],
3 => (object) ['id' => 3, 'name' => 'Alice']
];


_Is there a way to achieve this without looping through the array and creating a new one?_

Rate this post

4 of 5 based on 2205 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us