刚刚在这里遇到了麻烦,如果有人能帮助解决这个问题,我将不胜感激。
以防万一有人想知道我想要完成什么,我目前正在练习 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)
与 echo
和for($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/