创建以值为键的关联数组

时间:2016-04-20 14:22:49

标签: php

我有这个包含信息的数组,我想创建一个新的关联数组。关联数组中的每个键应该是旧键中的“名称”。在每个新密钥中,我希望收集相应的信息。

Array
(
    [0] => Array
        (
            [id] => 1
            [counter] => 21478813
            [serie] => 2607171234
            [name] => Ben
        )
    [1] => Array
        (
            [id] => 2
            [counter] => 21478858
            [serie] => 2607177151
            [name] => Evan
        )
    [2] => Array
        (
            [id] => 3
            [counter] => 21478817
            [serie] => 2607171341
            [name] => Steve
        )
    [3] => Array
        (
            [id] => 4
            [counter] => 21471798
            [serie] => 2607178561
            [name] => Ben
        )
    [4] => Array
        (
            [id] => 5
            [counter] => 21478811
            [serie] => 2607171347
            [name] => Ben
        )
)

这是我正在尝试创建的数组:

Array
(
    ["Ben"] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [counter] => 21478813
                    [serie] => 2607171234
                    [name] => Ben
                )
            [1] => Array
                (
                    [id] => 4
                    [counter] => 21471798
                    [serie] => 2607178561
                    [name] => Ben
                )
            [2] => Array
                (
                    [id] => 5
                    [counter] => 21478811
                    [serie] => 2607171347
                    [name] => Ben
                )
        )
    ["Evan"] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [counter] => 21478858
                    [serie] => 2607177151
                    [name] => Evan
                )
        )
    ["Steve"] => Array
        (
            [0] => Array
                (
                    [id] => 3
                    [counter] => 21478817
                    [serie] => 2607171341
                    [name] => Steve
                )
        )
)

2 个答案:

答案 0 :(得分:0)

使用foreach循环创建新数组:

$newArr = [];

foreach($myArr as $key => $value){
    $newArr[$myArr[$key][$value['name']]][] = $myArr[$key];
}

答案 1 :(得分:0)

View