我正在尝试以下内容:
我有一个特定的数字,我想将这个数字与一行中的数字进行比较,并得到每个数字的计数。
我有一个示例,它工作正常,但如果一行包含3个或更多相同的数字,并且在特定的数字中只有2个相同的数字,它将计数为3。
例如:
8 8 2 1 2 7 0
,在一行中有以下数字:
8 8 8 2 5 6
Count应为8= 1,8 = 1,8 =0;2= 1,5 = 0,6 =0
因为在特定的数字中只有2个数字8,所以第三个数字8不应该算在这一行中。
我希望它清楚:
下面是链接,解释起来可能会更清楚:
http://designer121.comze.com/sample.php可以使用count_chars()计算出特定数字中的字符,然后遍历行中的数字。在操作时,从指定的数字中减去计数或该数字,并且仅在计数大于零时设置标志(=1部分)。
EDIT:一些代码:
$number = '8821270';
$rows = '888256';
$count = array();
$digits = count_chars($number, 1);
foreach (str_split($rows) as $row) {
if (isset($digits[ord($row)]) && $digits[ord($row)] > 0) {
$count[] = 1;
$digits[ord($row)]--;
} else {
$count[] = 0;
}
}
var_dump($count);
如果我理解正确,你从db得到一个整数,并想知道哪些数字存在于预定义的数字中。你可以把这些整数转换成字符串字符串基本上是一个字符数组。因此,首先创建一个数组,其中包含预定义数字中的哪些数字和数量。然后逐个字符地遍历db number,看看它是否存在于预定义的number数组中。如果是,则减少该数字的计数。
代码可以像这样:
$number = 8821270;
$row = 888256;
//create string representation of integer
$n = (string)$number;
//calculate which numbers exist in the $number
$row_n = array();
for($i =0; $i < strlen($n);$i++){
$char = $n[$i];
if (isset($row_n[$char])) {
$row_n[$char]++;
}
else {
$row_n[$char] = 1;
}
}
/*
at this point $row_n is an array where the key is a digit from $number
and the value is the quantity
*/
//create string representation of fetched number
$s = (string)$row;
for($i =0; $i < strlen($s);$i++){
$char = $s[$i];
if (isset($row_n[$char]) && $row_n[$char] > 0) {
$result[] = array($char, 1);
$row_n[$char]--; //decrease count for that number
}
else {
$result[] = array($char, 1);
}
}
/*
Here result is an array with information on each separate number
Right now it looks like this:
array
0 => array
0 => digit
1 => status
1 => array
0 => digit
1 => status
Modify $result[] = array($char, 1); to make it look whatever you want
*/
您可以使用array_intersect_assoc,但是您必须首先将您的数字转换为数组:
$numberOne = '8821270';
for($i=0;$i< strlen($numberOne);$i++){
$numberOneArray[] = $numberOne[$i];
}
$numberTwo = '888256';
for($i=0;$i< strlen($numberTwo);$i++){
$numberTwoArray[] = $numberTwo[$i];
}
$result = array_intersect_assoc($numberOneArray, $numberTwoArray);
// display the result
print_r(array($numberOneArray, $numberTwoArray,$result));
由于函数保留键,现在可以从0