我有对象的关联数组。我想按对象字段值设置该数组中的关键点。我看到的所有问题都是关于分组的,但在我的情况下,这些值总是独一无二的。
我所拥有的:
<?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));
结果:
Array
(
[a] => stdClass Object
(
[key] => a
[xxx] => xxx
)
[b] => stdClass Object
(
[key] => b
[xxx] => xxx
)
[c] => stdClass Object
(
[key] => c
[xxx] => xxx
)
)
但有没有更好的方法,没有循环?最短的解决方案是什么?
您可以使用array_combine((和array_column((。
array_column()
获取密钥,array_combine()
使用提取的密钥和对象作为值来构建阵列。
$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));
输出:
Array
(
[a] => stdClass Object
(
[key] => a
[xxx] => xxx
)
[b] => stdClass Object
(
[key] => b
[xxx] => xxx
)
[c] => stdClass Object
(
[key] => c
[xxx] => xxx
)
)
查看工作演示。