PHP数组排序多维

时间:2014-11-19 21:31:05

标签: php arrays data-structures

我有一个像这样结构的数组(这是CSV格式化的方式):

Array(

    0 => Array(
        0 => person1
        1 => person2
        2 => person3
        //all the way to 9
    ),

    1 => Array(
        0 => id belonging to person 1
        1 => id belonging to person 2
        2 => id belonging to person 3
    ),

    2 => Array(
        0 => id belonging to person 1
        1 => id belonging to person 2
        2 => id belonging to person 3
    ),

    //all the way to 20
)

我正在尝试对一个新的数组(数组)进行排序,每个索引都是与上面0索引中的键对应的值。即,person1指向一个阵列,其中包含阵列1-20外部的所有ID。

在索引0之后的每个数组中,它包含20个ID,0属于第一个数组中的键0。

我想要实现的结构如下所示:

Array(
    [person1] => Array(
        id belonging to person 1
        id belonging to person 1
        id belonging to person 1
    ),

    [person2] => Array(
        id belonging to person 2
        id belonging to person 2
        id belonging to person 2
    ),

    [person3] => Array(
        id belonging to person 3
        id belonging to person 3
        id belonging to person 3
    ),
)

到目前为止,我的尝试已经奏效,但是,我不得不对一些索引进行硬编码。什么是实现理想结构的最佳解决方案?

1 个答案:

答案 0 :(得分:1)

我有点不确定这是不是你要找的......

<?php

$arr = Array(

    0 => Array(
        0 => "person1",
        1 => "person2",
        2 => "person3"
        //all the way to 9
    ),

    1 => Array(
        0 => "id belonging to person 1",
        1 => "id belonging to person 2",
        2 => "id belonging to person 3"
    ),

    2 => Array(
        0 => "id belonging to person 1",
        1 => "id belonging to person 2",
        2 => "id belonging to person 3"
    )
);

foreach($arr[0] AS $id=>$name)
{
    $ids[$id] = $name;
}

foreach(array_slice($arr,1) AS $persons)
{
    foreach($persons AS $id=>$person)
    {
        // make sure to check if $ids[$id] exist and handle it as you like.
        // if(isset($ids[$id]))
        $people[$ids[$id]][] = $person;
    }
}


print_r($people);

?>

结果:

Array
(
    [person1] => Array
        (
            [0] => id belonging to person 1
            [1] => id belonging to person 1
        )

    [person2] => Array
        (
            [0] => id belonging to person 2
            [1] => id belonging to person 2
        )

    [person3] => Array
        (
            [0] => id belonging to person 3
            [1] => id belonging to person 3
        )

)

编辑:应该注意我没有检查$ ids数组中是否存在此人的身份,而且如果设置了$ people则不会。