使用array_diff()比较两个数组的不同为何只返回了一个不同的元素?

WBOY
Release: 2016-06-23 13:37:51
Original
1236 people have browsed it

我取出数据库中不同表中相同字段的值分别两个不同的数组中,使用array_diff(),找出在数组1而不在数组2的的元素,为何只返回一个不同的元素?
代码如下:
error_reporting( E_ALL&~E_NOTICE );
header('Content-type:text/html; charset=utf-8');
date_default_timezone_set('Asia/Shanghai');
 require_once("init.php");
$sql="select * from dev_property";
$res=mysql_query($sql) or die(mysql_error());
$num_rows=mysql_num_rows($res);
while($sn=mysql_fetch_array($res))
{
$prime=array();
$prime[]=$sn["serial_number"];
for($i=0;$i {
echo $prime[$i];
echo "";
}

}
echo "";
$starttime = '08:25:00';
    $endtime = '23:35:00';
    $sql="select * from data where time>='".date('Y-m-d').' '.$starttime."' and time $result=mysql_query($sql) or die(mysql_error());
   while($date=mysql_fetch_array($result))
   {
   // $num_rows1=mysql_num_rows($result);
 
   
 $a=array();
     $a[]=$date["serial_number"];
             for($i=0;$i  {
 echo $a[$i];
     echo "";
 }


echo "";

}
$diff=array_diff($prime,$a);
for($i=0;$i echo $diff[$i];
   echo "";
   echo count($diff);
   echo "";
   ?>
执行结果:
数组$prime
862118028862461
862118028862462
862118028862463
862118028862464
数组$a
862118028862461
结果
862118028862464
1
按照我的本意返回的应该是
862118028862462
862118028862463
862118028862464
现在只返回了862118028862464,为什么?


回复讨论(解决方案)

你在 $diff=array_diff($prime,$a); 前打印一下数组

print_r($prime);print_r($a);$diff=array_diff($prime,$a);
Copy after login
Copy after login
看看都是什么

你在 $diff=array_diff($prime,$a); 前打印一下数组

print_r($prime);print_r($a);$diff=array_diff($prime,$a);
Copy after login
Copy after login
看看都是什么


谢谢,找到原因了,$prime=array();应放在while循环外,等于我每次while循环都初始化了数组,我的数据根本没全部存入数组中。
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!