只显示数组中的最后一项 [英] Foreach only showing last item in array

查看:140
本文介绍了只显示数组中的最后一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个foreach循环遍历数组中的每个项目,但它只捕获最后一个项目,不会遍历第一个项目。我已经精简了代码,只显示相关部分,并添加了一些命令,以确定问题,如上所述。

  $ message ==kk,ll; 
$ myArray = explode(',',$ message);

print_r($ myArray);

foreach($ myArray as $ value);
{
echo$ value< br>;
$ array [] = $ value;
}

print_r($ array);

输出结果为:

  Array([0] => kk [1] => ll)ll 
Array([0] => ll)

您可以看到当我使用 print_r()时,数组包含两个项目。但是 foreach 循环只能循环使用最后一项。将数组元素添加到循环中的新数组中也最终得到一个只包含最后一个元素的数组。我在做什么错了?

解决方案

在你的代码中有两个错误:


  1. 在第一行中,有两个等号,应该只有一个。

  2. 在您的foreach循环,你错误地把分号放在最后:

    $ b $ foreach($ myArray as $ value);



    这样做,foreach循环将运行,但是 {} / code>实际上放置在foreach循环之外,从而导致 $ value 只存储数组的最后一个元素。

    代码应该如下所示:

      $ message =kk ,二; 
    $ myArray = explode(',',$ message);
    print_r($ myArray);
    foreach($ myArray as $ value){
    echo$ value< br>;
    $ array [] = $ value;
    }
    print_r($ array);


    I'm attempting to make a foreach loop to iterate over each item in an array, but it only captures the last item and does not iterate over the first one. I've stripped down the code to only show the relevant parts and added some commands to identify the problem as described above.

    $message == "kk,ll";
    $myArray = explode(',', $message);
    
    print_r ($myArray);
    
    foreach ($myArray as $value);
    {   
        echo "$value <br>";
        $array[] = $value;
    }
    
    print_r ($array);
    

    The output is:

    Array ( [0] => kk [1] => ll ) ll 
    Array ( [0] => ll )
    

    You can see that when I use print_r() the array contains two items. But the foreach loop only loops over the last item. Adding the array elements into a new array inside the loop also ends up with an array containing only the last element. What am I doing wrong?

    解决方案

    You have two mistakes in you code:

    1. In your first line you have two equal signs which should only be one.

    2. In your foreach loop, you have by mistake put an semicolon at the end:

    foreach ($myArray as $value);

    Doing this, the foreach loop will run, but the code inside the {} is actually placed outside the foreach loop, and thereby causing $value only to store the last element of the array.

    The code should look like this:

    $message = "kk,ll";
    $myArray = explode(',', $message);
    print_r ($myArray);
    foreach ($myArray as $value) {   
        echo "$value <br>";
        $array[] = $value;
    }
    print_r ($array);
    

    这篇关于只显示数组中的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆