下面的代碼將得到所有組合,而無需重複:
$factor = 5;
$arr = range(1, $factor); // (1,2,3,4,5)
$f = array_product($arr);
$pairs = array();
$unique = array();
for($i = 1; $i < $f/2; $i++){ // only need to check until half (the other half would repeat the values
// if not divisable/already found
if($f % $i != 0 || isset($unique[$i]) || isset($unique[$f/$i])){
continue;
}
$pairs[] = array($i, $f/$i);
$unique[$i] = true;
}
結果($pairs
):
Array
(
[0] => Array
(
[0] => 1
[1] => 120
)
[1] => Array
(
[0] => 2
[1] => 60
)
[2] => Array
(
[0] => 3
[1] => 40
)
[3] => Array
(
[0] => 4
[1] => 30
)
[4] => Array
(
[0] => 5
[1] => 24
)
[5] => Array
(
[0] => 6
[1] => 20
)
[6] => Array
(
[0] => 8
[1] => 15
)
[7] => Array
(
[0] => 10
[1] => 12
)
)
看到它在行動here。
如果你需要像這個問題,你可以使用此代碼:
$p = array();
foreach($pairs as $pair){
$p[] = sprintf('(%s,%s)', $pair[0], $pair[1]);
}
結果($p
):
Array
(
[0] => (1,120)
[1] => (2,60)
[2] => (3,40)
[3] => (4,30)
[4] => (5,24)
[5] => (6,20)
[6] => (8,15)
[7] => (10,12)
)
旁註:你可以做到這一點第一個代碼 - 不需要爲此創建另一個循環(在$pairs[] = array($i, $f/$i);
之後,可以使用$p[] = sprintf('(%s,%s)', $i, $f/$i);
。
初始數組的相關性是什麼?它有什麼關係? – showdev
如果你只是想檢查數組中的值對:[https://eval.in/612448](https://eval.in/612448) – FirstOne
我只是不明白你爲什麼'10 ,12'和'6,20' ..也許你想自己也可以自己繁殖嗎? (如果是這樣,爲什麼不'8,15'?) – FirstOne