php for循环数组长度

我有这个数组:


array('Volvo', 'BMW', 'Toyota', 'Kijang');

我想要这样的结果


"Volvo","BMW","Toyota","Kijang"

"BMW","Volvo","Toyota","Kijang"

"Toyota","Volvo","BMW","Kijang"

"Kijang","Toyota","Volvo","BMW"

这是我的代码:


$products = array('Volvo', 'BMW', 'Toyota', 'Kijang');


$rows = count($products);  


for ($i = 0; $i < $rows; $i++) {


    echo $products[$i] . '<br>';

}

但是,不幸的是我错过了 3 个结果:


"BMW","Volvo","Toyota","Kijang"

"Toyota","Volvo","BMW","Kijang"

"Kijang","Toyota","Volvo","BMW"

如何获得错过的组合并完美适用于不同的数组长度?


三国纷争
浏览 114回答 2
2回答

波斯汪

您也可以通过这种方式实现这一目标。<?php&nbsp; &nbsp;$products = array('Volvo', 'BMW', 'Toyota', 'Kijang');&nbsp; &nbsp; &nbsp;for($i=0;$i<count($products);$i++){&nbsp; &nbsp; &nbsp; &nbsp; echo implode(", ",$products);&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; echo "<br>";&nbsp; &nbsp; &nbsp; &nbsp; array_push($products, array_shift($products));&nbsp; &nbsp; &nbsp;}?>这将为您提供以下结果:Volvo, BMW, Toyota, KijangBMW, Toyota, Kijang, VolvoToyota, Kijang, Volvo, BMWKijang, Volvo, BMW, Toyota您可以运行这里的代码。希望这会对您有所帮助。

茅侃侃

你可以通过这种方式来实现<?php$products = array('Volvo', 'BMW', 'Toyota', 'Kijang');foreach($products as $product){&nbsp; &nbsp; echo "'".$product."', ";&nbsp; &nbsp; foreach($products as $otherProduct){&nbsp; &nbsp; &nbsp; &nbsp; if($otherProduct == $product){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Skip the element&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; echo "'".$otherProduct."', ";&nbsp; &nbsp; }&nbsp; &nbsp; echo "<br>";}您需要循环两次才能得到结果。
打开App,查看更多内容
随时随地看视频慕课网APP