php将索引数组转换成关联数组

array_column不仅可以抽出索引数组的指定列,还可以将二维索引数组转换成关联数组。将方法的第二个参数设为null, 第三个参数为关联数组的key.
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$first_names = array_column($records, 'first_name');
Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)


$last_names = array_column($records, 'last_name', 'id');
Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)

$last_names = array_column($records, null, 'id');

Array
(
    [2135] => Array
        (
            [id] => 2135
            [first_name] => John
            [last_name] => Doe
        )

    [3245] => Array
        (
            [id] => 3245
            [first_name] => Sally
            [last_name] => Smith
        )

    [5342] => Array
        (
            [id] => 5342
            [first_name] => Jane
            [last_name] => Jones
        )

    [5623] => Array
        (
            [id] => 5623
            [first_name] => Peter
            [last_name] => Doe
        )

)

 

 

posted on 2021-03-18 11:26  冯亮  阅读(1191)  评论(0编辑  收藏  举报

导航