1

我有一个不同部门的多维数组,并且想使用 foreach 循环遍历它,但由于某种原因,foreach 循环在每次迭代中都会抓取第一个键下的值。

数组如下所示:

$departmentArray = 

Array
(
    [0] => Array
        (
            [dpt_id] => 5
            [dpt_name] => Administration
            [dpt_employees] => Array
                (
                [0] => Array
                    (
                        [started] => 2000-06-01
                        [stopped] => 9999-99-99
                        [empl_id] => 21
                    )

                [1] => Array
                    (
                        [started] => 2000-06-01
                        [stopped] => 2010-01-01
                        [empl_id] => 23
                    )
            )
    )

    [1] => Array
        (
            [dpt_id] => 6
            [dpt_name] => Warehouse
            [dpt_employees] => Array
                (
                [0] => Array
                    (
                        [started] => 2000-10-01
                        [stopped] => 2012-01-01
                        [empl_id] => 30
                    )

                [1] => Array
                    (
                        [started] => 2007-10-17
                        [stopped] => 9999-99-99
                        [empl_id] => 197
                    )
            )
    )
)

foreach 循环如下所示:

foreach($departmentArray as $key => $value) {

    print_r($key);
    print_r($value['dpt_name']);

}

这打印:

0 Administration 1 Administration. 

有谁知道,为什么循环不会在数组中向前移动并在第二次迭代期间获取键/索引 1 下的值(仓库)?

4

1 回答 1

2

彻底陷入黑暗:

您之前$valueforeach循环中使用过作为参考,如下所示:

foreach ($foo as &$value) { ... }

foreach ($departmentArray as $key => $value) { ... }

这是引用的一个众所周知的副作用。unset($value)在第一个循环之后。

于 2012-09-18T13:50:05.557 回答