为什么我的php foreach循环仅返回数组的最后一个值? [英] Why does my php foreach loop return only the last value of the array?

查看:91
本文介绍了为什么我的php foreach循环仅返回数组的最后一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在创建一个自定义的wordpress主题,并且陷入了foreach循环的问题.我在下面重新创建了一个简单的foreach循环,该循环代表我的wordpress网站遇到的问题.

I am currently creating a custom wordpress theme and have gotten stuck on an issue with a foreach loop. I have recreated a simple foreach loop below that represents the problem I'm having with my wordpress site.

我希望$ numbers的返回值为1 2 3 4,但是当我回显$ numbers时,它仅返回数字4.我在Stack Overflow上找到的其他答案指向不正确的分号或变量名被使用两次.您可以在下面看到情况并非如此,但该值仍然只是数组中的最后一个值.谁能解释我应对此代码进行哪些更改,以便$ numbers返回1 2 3 4?预先感谢.

I would expect the return value for $numbers to be 1 2 3 4, but instead when I echo $numbers, it only returns the number 4. Other answers I've found on Stack Overflow point to out of place semicolons or variable names being used twice. You can see below that this is not the case here but the value is still just the last value in the array. Can anybody explain what I should change about this code so that $numbers returns 1 2 3 4? Thanks in advance.

<?php

$my_arrays = [[1, 2],[3, 4]];
foreach($my_arrays as $array) {
  foreach($array as $a) {
    $numbers = $a . " ";
  }

}

echo $numbers;

?>

推荐答案

使用.=附加字符串.每次您使用 = 时,它都会使用.= 覆盖先前的值.

Use .= to append a string. Every time you were using = it was overriding the previous value, by using .= it will add it to the existing string.

<?php

$my_arrays = [[1, 2],[3, 4]];
foreach($my_arrays as $array) {
  foreach($array as $a) {
    $numbers .= $a . " "; //Use .= to append a string
  }

}

echo $numbers;

?>

这篇关于为什么我的php foreach循环仅返回数组的最后一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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