在数组中查找值assoaction

时间:2010-03-06 08:05:03

标签: php arrays

我有一个多维数组,子数组的重复值为' eduHisRowId ',如:

Array
(
    [0] => Array
        (
            [eduHisRowId] => 4
            [repOrderId] => 15
        )

    [1] => Array
        (
            [eduHisRowId] => 5
            [repOrderId] => 16
        )

    [2] => Array
        (
            [eduHisRowId] => 5
            [repOrderId] => 17
        )

    [3] => Array
        (
            [eduHisRowId] => 6
            [repOrderId] => 18
        )

    [4] => Array
        (
            [eduHisRowId] => 7
            [repOrderId] => 19
        )

    [5] => Array
        (
            [eduHisRowId] => 7
            [repOrderId] => 20
        )

    [6] => Array
        (
            [eduHisRowId] => 8
            [repOrderId] => 21
        )

)

现在我想要理清这些重复的值,以便我能够检查索引' [1] =>上的记录。数组'与索引' [2] =>上的记录相关联。数组'&此关联关系也将采用数组格式,如:

Array
    (
        [0] => Array
            (    
                [0] => 4
                [1] => Array
                    (
                        [0] => 15
                    ) 
            )

        [1] => Array
            (
                [0] => 15
                [1] => Array
                    (
                        [0] => 16
                        [0] => 17
                    )
            )

        [2] => Array
            (
                [0] => 6
                [1] => Array
                    (
                        [0] => 18
                    )
            )

        [3] => Array
            (
                [0] => 7
                [1] => Array
                    (
                        [0] => 19
                        [0] => 20
                    )
            )

        [4] => Array
            (
                [0] => 8
                [1] => Array
                    (
                        [0] => 21
                    )
            )

    )

其中第0个innre mos数组的索引将包含' eduHisRowId '值&第一个索引上的数组将包含' repOrderId '值。

提前致谢...

1 个答案:

答案 0 :(得分:3)

我可以提出不同的解决方案吗?那个看起来像这样的数组结构怎么样:

Array
(
    [4] => Array
           (
              [0] => 15
           ) 

    [5] => Array
           (
               [0] => 16
               [1] => 17
           )
 )

键是eduHisRowId值,值是相应repOrderId值的数组。

创建此数组将如下所示:

function consolidate($item, $key, $array) {
     $rowId = $item['eduHisRowId'];
     if(!array_key_exists($rowId, $array)) {
         $array[$rowId] = array();
     }
     $array[$rowId][] = $item['repOrderId'];
}

$result = array();

array_walk($dataArray, 'consolidate', &$result);

$dataArray是您的多维数组,结果数组位于$result

参考:array_walk()array_key_exists()