Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
are you missing a $? –  Ross Jun 15 '12 at 18:00
    
yeah sorry typo! there is a $ in my code. –  Mars J Jun 15 '12 at 18:04
    
@MarsJ you get empty because both array are empty –  mgraph Jun 15 '12 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 –  Mars J Jun 15 '12 at 18:09
add comment

1 Answer

up vote 2 down vote accepted

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);
        }
    }
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.