一试我注意到一些事情:
implode()
接受一个数组并变成一个字符串。根据$onlist
是什么,你可能想要explode()
(如果它是一个字符串)或者只是原样使用它(如果它是一个数组)。我将假定它是一个逗号分隔的字符串。
mysql_*
方法已被弃用。您应该使用替代品,例如mysqli_*
。
- MySQL查询获取所有行行,其中
id
为$newarray
。它应该取代id
为$key
的所有行。
- 由于您只对数据库中的
id
字段感兴趣,因此您只应该请求该列(否则,您无意中将所有其余列移动)。
- 它看起来像你的表
id
是一个独特的价值。你可以保存一些处理,然后抓住第一个返回的行(如果有的话)。
- 您正在重新设置
$existing
每次您检查一个新的id
。您只想在开始时重置一次。
- 您的功能
example
收到$link
从未使用的变量。
因此,基于这一切,这里是你的代码的版本,应该工作:
function example($link, $onlist)
{
// Convert the comma-separated string to an array
$newarray = explode(',', $onlist);
// Start an empty array
$existing = array();
// Collect all the ids that are found in the database
foreach ($newarray as $key)
{
$query = mysqli_query("SELECT `id` FROM `table` WHERE `id` = '" . $key . "';");
if($cz = mysqli_fetch_assoc($query))
{
$existing[] = $cz['id'];
}
}
// Get only the ids that were NOT found
$ex = array_diff($newarray, $existing);
return $ex;
}
一个与你的战略需要注意的重要一点是,你会做一个MySQL查询了每一个你想要匹配的ID。你也可以这样做在一个单一的查询,这往往会多获得更好的性能,特别是如果id
是一个索引到表:
function example($link, $onlist)
{
// Convert $onlist from "a,b,c,1,2,3" to "'a','b','c','1','2','3'"
$tmp_array = explode(',', $onlist);
$onlist = "'" . implode("','", $tmp_array) . "'";
// Start an empty array
$existing = array();
// Get *all* rows that have *any* of the IDs in $onlist
$query = mysqli_query("SELECT `id` FROM `table` WHERE `id` IN (" . $key . ");");
while($cz = mysqli_fetch_assoc($query))
{
$existing[] = $cz['id'];
}
// Keep only the ids that were NOT found
$ex = array_diff($newarray, $existing);
return $ex;
}
$现有阵列应该循环之外声明。并使用print_r或var_dump等调试函数检查$ existing数组的值。使用它,而不是内爆 – Sundar