简体   繁体   English

为什么我的php foreach循环仅返回数组的最后一个值?

[英]Why does my php foreach loop return only the last value of the array?

I am currently creating a custom wordpress theme and have gotten stuck on an issue with a foreach loop. 我目前正在创建一个自定义的wordpress主题,并且陷入了foreach循环的问题。 I have recreated a simple foreach loop below that represents the problem I'm having with my wordpress site. 我在下面重新创建了一个简单的foreach循环,它表示我的wordpress网站遇到的问题。

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. 我希望$ numbers的返回值为1 2 3 4,但是当我回显$ numbers时,它仅返回数字4。我在Stack Overflow上发现的其他答案都指向不正确的分号或变量名使用两次。 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? 谁能解释我应对此代码进行哪些更改,以便$ numbers返回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;

?>

alternative solution : 替代解决方案:

appending the array elements into an array, then implode them, this will prevent printing the 将数组元素附加到数组中,然后内爆它们,这将阻止打印 empty space at the end of the text. 文本末尾的空白处。

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

try to do this 尝试这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM