首页 > 解决方案 > PHP 根据对象的值定义数组的键

问题描述

使用 PHP,我有对象列表。每个对象都有id字段:

$myArray = [
    0 => Object{
        'id' => 1,
        'title' => 'My title 1'
    },
    1 => Object{
        'id' => 2,
        'title' => 'My title 2'
    },
    2 => Object{
        'id' => 6,
        'title' => 'My title 6'
    }
]

我想从id对象设置数组键而不需要额外的 foreach。我想要这个结果:

$myArray = [
    1 => Object{
        'id' => 1,
        'title' => 'My title 1'
    },
    2 => Object{
        'id' => 2,
        'title' => 'My title 2'
    },
    6 => Object{
        'id' => 6,
        'title' => 'My title 6'
    }
]

我认为这是可能的,array_map但我不知道该怎么做。我试过了,但它返回子数组:

$newArray = array_map(function($entry) {
    return [$entry->id => $entry];
}, $myArray);

// return :

[
    0 => [
        1 => Object{
            'id' => 1,
            'title' => 'My title 1'
        },
    ],
    1 => [
        2 => Object{
            'id' => 2,
            'title' => 'My title 2'
        },
    ],
    2 => [
        6 => Object{
            'id' => 6,
            'title' => 'My title 6'
        }
    ]
]

标签: php

解决方案


$myArray = array_column($myArray, null, 'id');

推荐阅读