PHP多维数组使用for内for来回显字符串

标签 php arrays

刚刚在这里遇到了麻烦,如果有人能帮助解决这个问题,我将不胜感激。

以防万一有人想知道我想要完成什么,我目前正在练习 PHP,因此下面的代码块不是我想要用于网站的内容。

我正在尝试加入$cars[0][0]$cars[1][0]来创建一个字符串:

"A cool car is the Ferrari F458 Super Car"

并让它跳转到下一个字符串,即 $cars[0][1]$cars[1][1]依此类推,直到echo运行完整$length数组项的数量。

使用下面的代码,当前显示的结果是:

echo "A cool car is the " . $cars[0][0] . " " . $cars[1][0] . " Super Car<br />";

这会重复 6 行,然后跳转到下一个数组项 [0][1][1][1]重复另外 6 行。

我试图让他们回显第一行并进入下一行,尝试将 echo 分开和写作for($a)echofor($b)之后的行是 echo 的其余部分,但事实证明情况更糟。我尝试了其他一些迭代,但有些是无效的。尝试在网上寻找任何内容,但找不到任何具体的内容。我能够实现的最佳结果是它重复相同的字符串 6 次,然后移动到 +1 .

注意:我已经能够使用关联数组在另一次练习中完成此任务,但为了本次练习,我尝试在不使用关联数组的情况下完成此任务,只是为了更好地理解使用整数。

<?php //Echoing arrays using integers standard method
$cars = array(array("Ferrari", "Lamborghini", "Aston Martin", "Mercedes",   "Maserati", "McLaren"), array("F458", "Aventador", "one-77", "GT", "GTS", "MP4-12C"));
$lengthOne = count($cars[0]);
$lengthTwo = count($cars[1]);
for($a = 0; $a < $lengthOne; $a++) {
    for($b = 0; $b < $lengthTwo; $b++) {
        echo "A cool car is the " . $cars[0][$a] . " " . $cars[1][$b] . " Super Car<br />";
    }
}
?>
<?php

任何和所有的帮助将不胜感激!!

编辑:$b现在是< $lengthTwo (但结果仍然相同)

编辑:已更改 $cars[1][$a][1][$b] (现在结果更加困惑)

最佳答案

使用单个循环并对两个子数组使用相同的索引:

代码:

<?php

  $cars = array(
    array("Ferrari", "Lamborghini", "Aston Martin", "Mercedes",   "Maserati", "McLaren"), 
    array("F458", "Aventador", "one-77", "GT", "GTS", "MP4-12C")
  );
  $length = min (count ($cars[0]), count ($cars[1]));  /* In case the arrays have different lengths. */
  for($a = 0; $a < $length; $a++) {
    echo "A cool car is the " . $cars[0][$a] . " " . $cars[1][$a] . " Super Car\n";
  }

输出:

A cool car is the Ferrari F458 Super Car
A cool car is the Lamborghini Aventador Super Car
A cool car is the Aston Martin one-77 Super Car
A cool car is the Mercedes GT Super Car
A cool car is the Maserati GTS Super Car
A cool car is the McLaren MP4-12C Super Car

关于PHP多维数组使用for内for来回显字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27196694/

相关文章:

仅包含特定类对象的 PHP 数组

php - 从 XML 文件更新 MySQL 数据库

ruby - 在 Ruby 中从一个数组中减去另一个数组

c - O(n) 时间内的双维数组排序

PHP 在 URL 中传递两个 id

javascript - Ajax 请求 ($.ajax(type :'GET' )) 不会传递大于 45 的数组,但是 ($.ajax(type :'POST' )) 会传递。为什么?

php - in_array 函数未给出预期结果

php - 通过 MySQL 模式还是 PHP 检查输入数据?

javascript - jquery ajax返回HTML元素

php - 在 PHP 中使用命名空间解析 XML 数据