开发者

How do i Have the array values saved outside the foreach loop

i have a foreach loop when looping through that I am creating a $data array which holds all values

foreach ($this->arr1['somevalue']['object'] as $record ){                
    $data_add = array(
    'CODE' => $record['CODE'],
    'some_key' => $this->arr['somevalue'],
    'lines' => count($this->arr['somevalue']['object'])    
    );
       }
       var_dump($data_add);

Now when I say var_dump($data_add) Iam getting only the 开发者_StackOverflow中文版last value for "CODE" key .The above loop repeats for 3 times That means i will have 3 values .But iam getting only the third value.1st and 2nd values are not displayed. How do i get the values.I have an idea saying creating an array(record['CODE']) but did not work out.


Change:

$data_add = array(
    'CODE' => $record['CODE'],
    'some_key' => $this->arr['somevalue'],
    'lines' => count($this->arr['somevalue']['object'])    
    );

to:

$data_add[] = array(
    'CODE' => $record['CODE'],
    'some_key' => $this->arr['somevalue'],
    'lines' => count($this->arr['somevalue']['object'])    
    );


Try this:

foreach ($this->arr1['somevalue']['object'] as $record ){                
  $data_add[] = array(
    'CODE' => $record['CODE'],
    'some_key' => $this->arr['somevalue'],
    'lines' => count($this->arr['somevalue']['object'])    
  );
}


If you amend the code in order that $data_add becomes an array:

foreach ($this->arr1['somevalue']['object'] as $record ){                
    $data_add[] = array(
    'CODE' => $record['CODE'],
    'some_key' => $this->arr['somevalue'],
    'lines' => count($this->arr['somevalue']['object'])    
    );
       }
       var_dump($data_add);

This should work fine.


the problem you have is that you are overwriting the $data_add variable each iteration, and thus you only keep the last, to obtain all answers you could use an array (as proposed by the others)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜