【问题标题】:Array of objects - set keys by object field value对象数组 - 按对象字段值设置键
【发布时间】:2022-01-07 20:06:48
【问题描述】:

我有关联的对象数组。我想通过对象字段值在该数组中设置键。我看到的所有问题都是关于分组的,但就我而言,这些值始终是唯一的。

我有什么:

<?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
        )
)

但是有没有更好的方法,没有循环?什么是最短的解决方案,一些单行?

【问题讨论】:

    标签: php arrays object


    【解决方案1】:

    您可以使用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
            )
    
    )
    

    查看working demo。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2015-11-28
      • 2011-05-16
      相关资源
      最近更新 更多