我在组合数组值方面遇到了麻烦。我已经尝试将它们组合起来并做出我已经做过的事情,但我想要删除一些我不想要的对。请有人来帮我这件事。
// the Code I have now is:
$inputarray = array('Mussafiri', 'Fire', 'Ubungo', 'Mbezi');
$outputarray = array();
$i = 0;
foreach($inputarray as $values) {
$j = 0;
foreach($inputarray as $values2) {
if($values != $values2){
$outputarray[] = array($values => $values2);
}
$j++;
}
$i++;
}
print_r($outputarray);
//Output array is:
Array ( [0] => Array ( [Mussafiri] => Fire)
[1] => Array ( [Mussafiri] => Ubungo)
[2] => Array ( [Mussafiri] => Mbezi)
[3] => Array ( [Fire] => Mussafiri)
[4] => Array ( [Fire] => Ubungo)
[5] => Array ( [Fire] => Mbezi)
[6] => Array ( [Ubungo] => Mussafiri)
[7] => Array ( [Ubungo] => Fire)
[8] => Array ( [Ubungo] => Mbezi)
[9] => Array ( [Mbezi] => Mussafiri )
[10] => Array ( [Mbezi] => Fire)
[11] => Array ( [Mbezi] => Ubungo) )
NOTE: I DO NOT WANT THE FOLLOWING PAIRS TO APPEAR, I want element to pair with the next element and not pair with the previous element so i do not like index 3,6,7,8,9,10 and 11 to appear in the pair list i.e
[3] => Array ( [Fire] => Mussafiri)
[6] => Array ( [Ubungo] => Mussafiri)
[7] => Array ( [Ubungo] => Fire)
[8] => Array ( [Ubungo] => Mbezi)
[9] => Array ( [Mbezi] => Mussafiri)
[10] => Array ( [Mbezi] => Fire)
[11] => Array ( [Mbezi] => Ubungo)
答案 0 :(得分:0)
如果我理解正确,你试图从数组中创建所有唯一的对,在这种情况下,这样的东西应该有效:
$pairs = array();
foreach ($inputarray as $key => $value) {
for ($i = $key + 1; isset($inputarray[$i]); $i++) {
$pairs[] = array($value => $inputarray[$i]);
}
}
for循环将$i
设置为当前数组元素的键+ 1,因此它永远不会引用自身,并且永远不会引用任何先前的数组成员。
答案 1 :(得分:0)
for($i=0; $i<$inputarray.length;$i++){
$k=$i+1;
for($j=$k; $j<$inputarray.length;$j++){
$outputarray[] = array($inputarray[$i] => $inputarray[$j]);
}
}