2014-01-06 17:09
浏览 475


I am wondering how can I store all values from a foreach loop, I know that I am re-initialising in the loop but I'm not sure how to store the data. Heres my basic loop:

$array = array("v1", "v2", "v3", "v4");
foreach($array as $row){
    $arr = array('val' => $row);
    echo $row;

So when I use the print_r($arr) the only thing outputted would be v4 and I know that the values are there because the echo $row; does return each output individually.

My question would be how can I store each instance of row in my array?

图片转代码服务由CSDN问答提供 功能建议

我想知道如何存储来自foreach循环的所有值,我知道我正在重新初始化 循环,但我不知道如何存储数据。 继承我的基本循环:

  $ array = array(“v1”,“v2”,“v3”,“v4”); 
foreach($ array as $ row)  {
 $ arr = array('val'=> $ row); 
 echo $ row; 
nprint_r($ arr); 

所以当我使用 print_r($ arr)时,输出的唯一内容就是 v4 ,我知道值是因为 echo $ row; < / code>确实单独返回每个输出。


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongxin8392 2014-01-06 17:11

    Create a new array, fill it:

    $array = array("v1", "v2", "v3", "v4");
    $newArray = array();
    foreach($array as $row){
        // notice the brackets
        $newArray[] = array('val' => $row);
    打赏 评论
  • dpf71390 2014-01-06 17:17

    It looks like you are storing your array wrong.

    Try adjusting the $arr = array('val' => $row);


    $arr[] = array('val' => $row);

    This will set it so you pick up each line as a separate array which you can easily navigate through.

    Hope this helps!

    打赏 评论
  • dqkkrt8860 2014-01-06 17:45

    If I'm reading correctly, you want to transform your array from simple values to key-value pairs of 'val'->number. array_map is a concise way of doing this sort of transformation.

    $array = array("v1", "v2", "v3", "v4");
    $arr = array_map(function($v) { return array('val'=>$v); }, $array);

    While it doesn't matter in this case, array_map also has the handy feature of preserving your keys, in case that is desired.

    Note that you can also provide a named function to array_map, instead of providing the implementation inline, which can be nice in the event that your transform method gets more complicated. More on array_map here.

    打赏 评论

相关推荐 更多相似问题