0

我是 php 新手,不知道为什么这不起作用。有人可以帮助我吗?谢谢!我的代码如下:

if (!$this->_in_multinested_array($over_time, $request_year)) {
            $temp = array('name'=>$request_year, 'children'=>array());
            array_push($over_time, $temp);
        }

        if (!$this->_in_multinested_array($over_time, $request_month)) {

            $child = array('name'=>$request_month, 'children'=>array());

            foreach ($over_time as $temp) {

                if ($temp['name'] == $request_year) {
                   array_push($temp['children'], $child);
                }
            }
        }

每当我检查这段代码的结果时,temp['children']数组总是空的,即使它不应该是空的。

4

1 回答 1

2

此循环中的每个 $temp 都是一个副本:

    foreach ($over_time as $temp) {

        if ($temp['name'] == $request_year) {
           array_push($temp['children'], $child);
        }
    }

您想更改数组而不是复制,因此您必须使用参考:

    foreach ($over_time as &$temp) {

        if ($temp['name'] == $request_year) {
           array_push($temp['children'], $child);
        }
    }
于 2012-06-15T18:52:14.517 回答