PHP多维数组 - 显示最后一个数组的foreach循环

时间:2021-04-28 21:35:18

I have a multidimensional array as follow:-

我有一个多维数组如下: -

$worksheet = array(
  'sheet 1' => array(
    '#1 sheet 1',
    ' #2 sheet 1',
    '#3 sheet 1'
  ),

  'sheet 2' => array(
    '#1 sheet 2',
    '#2 sheet 2'
  ),

  'sheet 3' => array(
    '#1 sheet 3',
    '#2 sheet 3'
  )
);

then I run PHP code as below:

然后我运行PHP代码如下:

foreach($worksheet as $ws=>$value)
  echo $ws.'<br/>';
{
  foreach($value as $sheet=>$ivalue)
  {
    echo $ivalue.'<br/>';
  }
}

Above code will generate only the last array like follow:

上面的代码将只生成最后一个数组,如下所示:

sheet 1,  sheet 2,  sheet 3,  #1 sheet 3,  #2 sheet 3

what had happen to my:

发生了什么事:

#1 sheet 1, #2 sheet 1, #3 sheet 1, #1 sheet 2, #2 sheet 2.

3 个解决方案

#1


1  

Fix your syntax. echo is not inside the {}s as you intend. Otherwise, PHP will assume that you just intend to do the echo, and won't realize you want to do an internal loop.

修复你的语法。 echo不在你想要的{}内。否则,PHP将假设您只是打算进行回显,并且不会意识到您想要进行内部循环。

To fix:

修理:

foreach($worksheet as $ws=>$value)
{
     echo $ws.'<br/>';

#2


1  

Because you did a mistake. The second and the third lines of your code are reversed. The code should be like this:

因为你犯了一个错误。代码的第二行和第三行是相反的。代码应该是这样的:

foreach($worksheet as $ws=>$value)
{
         echo $ws.'<br/>';

Thus, your code is looping with the external foreach through the echo and then, in a "section" enclosed by the brackets {, is doing another loop (the inner foreach).

因此,您的代码通过回显与外部foreach循环,然后,在括号{括起来的“部分”中,正在执行另一个循环(内部foreach)。

#3


1  

echo $ws.'<br/>'

should be inside the brackets

应该在括号内

#1


1  

Fix your syntax. echo is not inside the {}s as you intend. Otherwise, PHP will assume that you just intend to do the echo, and won't realize you want to do an internal loop.

修复你的语法。 echo不在你想要的{}内。否则,PHP将假设您只是打算进行回显,并且不会意识到您想要进行内部循环。

To fix:

修理:

foreach($worksheet as $ws=>$value)
{
     echo $ws.'<br/>';

#2


1  

Because you did a mistake. The second and the third lines of your code are reversed. The code should be like this:

因为你犯了一个错误。代码的第二行和第三行是相反的。代码应该是这样的:

foreach($worksheet as $ws=>$value)
{
         echo $ws.'<br/>';

Thus, your code is looping with the external foreach through the echo and then, in a "section" enclosed by the brackets {, is doing another loop (the inner foreach).

因此,您的代码通过回显与外部foreach循环,然后,在括号{括起来的“部分”中,正在执行另一个循环(内部foreach)。

#3


1  

echo $ws.'<br/>'

should be inside the brackets

应该在括号内