【问题标题】:Output another array inside a foreach loop?在 foreach 循环中输出另一个数组?
【发布时间】:2011-04-26 22:56:01
【问题描述】:

我有一个这样的 foreach 循环:

$test_array = array(1, 2, 3, 4, 5);

foreach($categories as $category)
{ 
    echo $category; // outputs cat one cat two cat three cat four cat five etc
    echo $test_array; // outputs Array Array Array Array Array
}

这显示得很好。

但我也想输出 test_array 数组,但是当我这样做时,它会显示“Array Array Array Array Array Array”以及我的类别:(

如何让 test_array 也显示在我的 foreach 循环中?

【问题讨论】:

  • 你的意思是每次显示所有元素,还是每个类别一个?
  • 你能发布你使用的输出'Array Array etc'的代码吗?
  • @cHao 同时显示类别数组和 test_array
  • @Keith:这并不能真正回答问题。你想要“猫一 1 2 3 4 5 猫二 1 2 3 4 5”或“猫一猫二.... 1 2 3 4 5”?
  • @cHao: stackoverflow.com/questions/5797436/… 这样,这似乎工作得很好!

标签: php arrays loops foreach


【解决方案1】:

如果你的答案是你想要的,并且如果你没有对数组索引做奇怪的事情,那么你可以说

foreach ($categories as $index => $category)
{
      echo $category, $test_array[$index];
}

但请注意,这取决于两个数组都具有顺序的数字索引。像array(2, 5, 10) 这样定义的数组可以正常工作,$arr[] = $some_value; 构建的数组也是如此。但如果您使用非数字键或乱序添加它们,您可能会遇到问题。

【讨论】:

    【解决方案2】:

    使用print_r 函数。

    【讨论】:

    • 或者更好的是var_dump,这样您就可以看到类型和值可以处理空字符串(如false
    • 无论如何我可以以“正常方式”输出 test_array 吗?
    【解决方案3】:

    试试这个嵌套循环。我想它会做你想做的。

    $loopCount = 0;
        foreach($categories as $category) { 
          echo $category;
          if($count <5) {          
           foreach($test as $someInt) {
             echo $someInt;
             $count++;
            }
          }
        }
    

    【讨论】:

    • 谢谢,无论如何限制 test_array 被调用 5 次?
    • 见上面的编辑。我添加了一个循环计数器。这是你想要它做的吗?
    【解决方案4】:

    我个人更喜欢var_dump。祝你好运!

    【讨论】:

    • 无论如何我可以以“正常方式”输出 test_array 吗?
    • 您可以在调用 var_dump 之前输出一个
       标签。这将使输出预先格式化。此外,如果您在浏览器中“查看源代码”,它会显示一个漂亮的预格式化输出。
    【解决方案5】:

    我想出了一个解决方案:

    $test_array = array(1, 2, 3, 4, 5);
    
    $i=-1;
    foreach($categories as $category)
    { 
        $i++;
        echo $category; // outputs cat one cat two cat three cat four cat five etc
        echo $test_array[$i]; // outputs Array Array Array Array Array
    }
    

    这行得通,但是可以吗?

    【讨论】:

    • 取决于你想要达到的结果:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 2021-01-22
    • 2012-02-10
    • 1970-01-01
    相关资源
    最近更新 更多