2015-11-05 55 views
2

我不知道如何正確解釋我正在嘗試做什麼,但我嘗試使用示例來解釋。PHP Combine單一陣列

$products = array("35","37","43"); 

說如果我有上面的數組,我該如何創建一個結果數組,看起來像這樣。

$related_products = array (

array (35,37), 

array (35,43), 

array (37,35), 

array (37.43), 

array (43,35), 

array (43, 37)) 

回答

5

你可以使用兩個循環來捕獲所有組合:

$products = array("35","37","43"); 
$result = array(); 
for($i = 0; $i < count($products); $i++) { 
    for($j = 0; $j < count($products); $j++) { 
     if($i !== $j) { 
      $result[] = array(
       $products[$i], 
       $products[$j] 
      ); 
     } 
    } 
} 

print_r($result); 

結果:

Array 
(
    [0] => Array 
     (
      [0] => 35 
      [1] => 37 
     ) 

    [1] => Array 
     (
      [0] => 35 
      [1] => 43 
     ) 

    [2] => Array 
     (
      [0] => 37 
      [1] => 35 
     ) 

    [3] => Array 
     (
      [0] => 37 
      [1] => 43 
     ) 

    [4] => Array 
     (
      [0] => 43 
      [1] => 35 
     ) 

    [5] => Array 
     (
      [0] => 43 
      [1] => 37 
     ) 

) 
+0

卓越的邏輯,+1 – Pupil

0

你可以簡單地使用array_push方法像這樣的項目添加到主陣列,

$products = array("35","37","43"); 
$data = array(); 
for($i = 0; $i < count($products); $i++) { 
    for($j = 0; $j < count($products); $j++) { 
     if($i !== $j) { 
       array_push($data,array($products[$i],$products[$j])); 
      ); 
     } 
    } 
} 

print_r($data);