我有两个比较两个值(例如$sid1和$sid2),并匹配它们并找出相似和不同值的总数(我指的是计算值)。请帮我把代码给我
1)将从while循环中获取的值存储在数组中。
2)比较两个数组的相似值和不同值。
**My Program**
$sql="select * from table1 where qn1='$op2'";
$ds=mysql_query($sql);
while ($r=mysql_fetch_array($ds)) {
$sid1=$r[‘a’];
//need correct syntax for the below
$a[]= $sid1;
}
$sql2="select * from table2 where qn4='$op3'";
$ds2=mysql_query($sql2);
while ($r2=mysql_fetch_array($ds2)) {
//need correct syntax for the below
$sid2=$r2[‘a’];
$b[]= $sid2;
}
//how to match the array and count
Array ($a[] == $b[])
发布于 2014-12-27 05:10:27
首先,你的第一行是错的。使用#My Program
而不是**my program**
,也可以将结果直接存储到数组中。请记住,mysql()
已经脱离了php
,所以您应该使用mysqli()
功能。对于您的建议,您应该使用array_intersect()
函数。它返回一个匹配项数组。您可以使用sizeof()
函数来计算匹配项的数量,所以代码应该如下所示:
<?php
$sql="select * from table1 where qn1='$op2'";
$ds=mysqli_query($connection,$sql);
while ($r=mysqli_fetch_assoc($ds))
{
$a[]= $r['a'];
}
$sql2="select * from table2 where qn4='$op3'";
$ds2=mysqli_query($connection,$sql2);
while ($r2=mysqli_fetch_assoc($ds2))
{
$b[]= $r2['a'];
}
$match_items=array_intersect($a, $b);
$count=sizeof($match_items);
?>
发布于 2014-12-27 07:11:18
下面的程序可以帮助你。
当在SQL中选择*时,SQL表可能有多个列,从而产生如下所示的多维数组。
array (size=200)
0 =>
array (size=10)
'id' => string '18' (length=2)
'email' => string 'abc@xyz.com' (length=11)
'userName' => string 'abc' (length=3)
1 =>
array (size=10)
'id' => string '19' (length=2)
'email' => string 'cdf@xyz.com' (length=11)
'userName' => string 'cdf (length=3)
2=>
....
3=>
....
然后,您必须检查,一个表的整行是否与、另一个表、整个行相匹配。所以你可以通过下面的方法来实现它。
<?php
// DB Connection
$db = new PDO( 'mysql:host=HOSTNAME;dbname=DB_NAME;charset=utf8', 'DB_USER_NAME', 'DB_PASSWORD', array( PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) );
//Queries
$sql_query1 = "SELECT * FROM TABLE1 WHERE `qn1` = 'ABC';";
$sql_query2 = "SELECT * FROM TABLE2 WHERE `qn2` = 'XYZ';";
$data1 = $db -> query( $sql_query1 ) -> fetchAll( PDO::FETCH_ASSOC );
$data2 = $db -> query( $sql_query2 ) -> fetchAll( PDO::FETCH_ASSOC );
$notFound = array();
$found = array();
foreach ($data1 as $key => $value1) {
foreach ($data2 as $key => $value2) {
if( array_diff( $value1, $value2 ) ){
// NotFound Array
$notFound[] = $value1;
} else {
// Found Array
$found[] = $value1;
}
}
}
echo "Not Found data1 Elements in data2 : " . count( $notFound ) . "\n<br/> Found data1 Elements in data2 :" . count( $found ) ;
https://stackoverflow.com/questions/27667305
复制相似问题