我想創建一個 for 回圈來制作這樣的模式。
* two tree four five
one * tree four five
one two * four five
one two tree * five
one two tree four *
* * tree four five
one * * four five
one two * * five
one two tree * *
* * * four five
one * * * five
one two * * *
* * * * five
one * * * *
* * * * *
相反,我最終找到了如何使用 for 回圈獲取這些模式
這些家伙正在使用JavaScript:
const temp = ["one","two","three","four","five"];
let arrayResult = []
for(let i = 0; i< temp.length; i ){
for(let j = 0; j< temp.length - i; j ){
let tempArr = temp.slice();
let stars = Array(i 1).fill('*')
tempArr.splice(j, i 1, ...stars);
arrayResult.push(tempArr);
}}
我想使用 php 來解決這個問題,但即使使用 array_splice() 我似乎也無法讓它作業
$temp = array("one","two","three","four","five");
$arrayResult = array();
for($i = 0; $i< count($temp); $i ){
for($j = 0; $j< count($temp) - $i; $j ){
$tempArr = $temp.slice();
$stars = Array($i 1).fill('*')
$tempArr.splice($j, $i 1, ...$stars);
$arrayResult [] = $tempArr;
}}
uj5u.com熱心網友回復:
你可以這樣做:
<?php
$temp = array("one","two","three","four","five");
$arrayResult = array();
for($i = 0; $i< count($temp); $i ){
for($j = 0; $j< count($temp) - $i; $j ){
$tempArr = $temp; //assign original array to temp variable
$newArray[$i 1] = '*'; //create a new star array
array_splice($tempArr,$j, $i 1,$newArray); //fill the stars into temp array
$arrayResult [] = $tempArr; //assign temp array to final output array
}
}
print_r($arrayResult);
輸出:https ://3v4l.org/9KRYJ
注意:如果您運行腳本并對console.log每個變數執行操作,您可以輕松了解發生了什么以及如何將其轉換為 PHP 代碼。我也是這樣做的。
uj5u.com熱心網友回復:
$template=explode(' ','one two tree four five');
//$template=['one', 'two', 'tree', 'four', 'five'];
for($i=5;($i-->0);)for($pos=0;$pos <=$i;) $res[]=array_replace($template,array_fill($pos-1,5-$i,'*') );
echo '<pre>';
//print_r($res);
var_dump($res);
echo '</pre>';
uj5u.com熱心網友回復:
<?php
$result = [];
$temp = ["one", "two", "three", "four", "five"];
for ($i = 0; $i < count($temp); $i ) {
for ($j = 0; $j < count($temp) - $i; $j ) {
$tempArr = $temp;
$stars[$i 1] = "*";
array_splice($tempArr, $j, $i 1, $stars);
array_push($result, $tempArr);
}
}
echo "<pre>";
print_r($result);
echo "</pre>";
希望這可以幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/505795.html
標籤:php
上一篇:使用Sum特定值鍵合并陣列
