今天我在编码过程中遇到了一个难题。我想和你分享并得到你的帮助。
我在MySql数据库中进行查询并获得结果,就像在数组中一样。所以我有这样的输出:
$rows=array(n) { // for each n value elements can have different values
["val1"] => string(3) "abc"
["val2"] => string(3) "def"
["val3"] => string(3) "ghi"
["val4"] => string(3) "jkl"
}例如,假设是n=4,我需要创建唯一的对,这样队列中不会出现相同数量的对。
我需要的是这个例子:
n= 1, 2, 3, 4我需要得到的一对:
1-2, 1-3, 1-4, 2-3, 2-4, 3-4我需要避免像2-1. 3-1, 4-1, 3-2, 4-2, 4-3 and 1-1, 2-2, 3-3, 4-4这样的一对。
对于每一对,我将检查这对数组是否相等。
我怎么能这么做?
发布于 2013-11-15 01:27:45
<?php
$n = 4;
for($i = 1; $i<=$n; $i++)
for($x = 1; $x<=$n; $x++)
if($i != $x && !isset($array[$x][$i]))
$array[$i][$x] = '';
//echo '<pre>';
//var_dump($array);
//echo '</pre>';
?>输出使用
<?php
for($i = 1; $i<=$n; $i++)
for($x = 1; $x<=$n; $x++)
if(isset($array[$i][$x]))
echo $i.'-'.$x.', ';
?>这将是:
如果是$n = 4
1-2,1-3,1-4,2-3,2-4,3-4,
如果是$n = 10
1-2、1-3、1-4、1-5、1-6、1-7、1-8、1-9、1-10、2-3、2-4、2-5、2-6、2-7、2-8、2-9、2-10、3-4、3-5、3-6、3-7、3-8、3-9、3-10、4-5、4-6、4-7、4-8、4-9、4-10、5-6、5-7、5-8、5-8,5-9、5-10、6-7、6-8、6-9、6-10、7-8、7-9、7-10、8-9、8-10、9-10,
发布于 2013-11-15 01:40:23
我正在使用数组,一旦所有的对都做好了,我就移除元素,可能有一个更好的解决方案,只使用
$n = 5;
$array = array("abc","def","ghi","jkl","mno");
$r_temp = $array;
$r_result = array();
foreach($array as $r){
$i = 0;
while($i < $n-1){
array_push($r_result,$r_temp[0].$r_temp[$i+1]);
$i++;
}
$n--;
array_shift($r_temp); //Remove the first element since all the pairs are used
}
print_r($r_result);产出将
Array ( [0] => abcdef [1] => abcghi [2] => abcjkl [3] => abcmno [4] => defghi [5] => defjkl [6] => defmno [7] => ghijkl [8] => ghimno [9] => jklmno )发布于 2022-03-01 18:01:26
这是一个老问题,但是它看起来是XY问题的一个很好的例子。
首先,直接回答你的问题:
$n = 4;
$pairs = [];
for ($i = 1; $i <= $n; ++$i) {
for ($j = $i+1; $j <= $n; ++$j) {
$pairs[] = [$i, $j];
}
}(您可以检查它这里)。
但是,,,如果我正确地理解了您正在寻找的内容,那么直接使用和SQL查询就更容易了:
SELECT mycolumn, COUNT(*) AS total FROM mytable GROUP BY mycolumn HAVING total > 1;此查询将返回列mytable.mycolumn的所有重复条目和外观数。
https://stackoverflow.com/questions/19991710
复制相似问题