2011-11-27 67 views
1

我有2 array datas("a","b","c")("x","y","z"),如何把它們混合和出把結果作爲(ax)|(ay)|(az)|(bx)|(by)|(bz)|(cx)|(cy)|(cz)? (每個$array1 + $array2合併成一個新單詞)。PHP 2的foreach結果混合

$array1 = array("a","b","c"); 
foreach($array1 as $data1){ 

} 
$array2 = array("x","y","z"); 
foreach($array2 as $data2){ 

} 
//$output = '(ax)|(ay)|(az)|(bx)|(by)|(bz)|(cx)|(cy)|(cz)'; 

回答

6

你要使用嵌套循環:

$items = array(); 

foreach($array1 as $a) 
{ 
    foreach($array2 as $b) 
    { 
     $items[] = '(' . $a . $b . ')'; 
    } 
} 
echo implode('|', $items); // (ax)|(ay)|(az)|(bx)|(by)|(bz)|(cx)|(cy)|(cz) 
7
<?php 

$array1 = array("a","b","c"); 
$array2 = array("x","y","z"); 

$array3 = array(); 

foreach($array1 as $data1){ 
    foreach($array2 as $data2){ 
     $array3[] = "($data1$data2)"; 
    } 
} 

echo implode('|', $array3); 

// (ax)|(ay)|(az)|(bx)|(by)|(bz)|(cx)|(cy)|(cz) 
8
$array = array(); 
$array1 = array("a","b","c"); 
$array2 = array("x","y","z"); 
foreach($array1 as $data1){ 
foreach($array2 as $data2){ 
    $array[] = '('.$data1.$data2.')'; 
} 
} 
echo implode('|', $array);