0

I am new to php and am not sure why this isn't working. Could someone help me? Thanks! My code is below:

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);
                }
            }
        }

Whenever I check the result of this code the temp['children'] array is always empty even though it shouldn't be.

3
  • yeah sorry typo! there is a $ in my code. Commented Jun 15, 2012 at 18:04
  • @MarsJ you get empty because both array are empty Commented Jun 15, 2012 at 18:05
  • $temp['children'] is an empty array definitely although I would like to populate it with the $child arrays. Those are not empty though Commented Jun 15, 2012 at 18:09

1 Answer 1

2

Each $temp in this loop is a copy:

    foreach ($over_time as $temp) {

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

You want to change the array instead of making a copy, so you have to use a reference:

    foreach ($over_time as &$temp) {

        if ($temp['name'] == $request_year) {
           array_push($temp['children'], $child);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.