我有一个循环中的数据流。这将从数据库中逐行检索结果。但是,我想在流和给定数组之间设置一种形式的数组差异。给定的数组是一个排除列表,例如黑名单用户列表。这就是目前为止的内容
这是一个虚构的例子。我不想写所有的数据库代码逐行检索结果
database objects containing ("Volvo","BMW","Toyota"); //assume that this is a continous stream of data from a database where we don't know the total elements. Just that single element
$toys=array("BMW","Toyota"); //assume that this is a list of blacklisted users
for($rindex=0; $rindex < count($cars); $rindex++)
{
for($index=0; $index < size(database objects); $index++)
{
//obtain the database object on a row by row basis
if (strcmp ( $cars[$rindex] , $toys[$index] )!=0) //specify exclusion
{
echo $cars[$rindex];
}
}
}
期望答案应为Volvo
。如果我们知道$cars
中的所有元素,这很容易做到,所以我们不能用array-diff($cars,$toys)
。假设$cars
是一个连续的流,即一个逐行的数据库结果。我们如何在固定已知的黑名单数组和连续数据流之间执行array-diff()
请记住,array-diff()
不能使用,因为我们在开始时不知道数据流的全部大小或流中所有元素的大小。
这可以使用array-filter()
完成,但我已经有性能问题,并希望在线执行此操作。
请在PHP中提供答案
快速查找数组-代码被注释和测试。PHP 5.3.18
<?php // Q22754093
// database objects containing ("Volvo","BMW","Toyota"); //assume that this is a continous stream of data from a database where we don't know the total elements. Just that single element
$allToys = array("Volvo","BMW","Toyota");
// use the 'toy' as the array key -- there is no faster way of checking whether
// something is in an array, especially if the array is large.
$badToys = array("BMW" => true,
"Toyota" => true); //assume that this is a list of blacklisted users
// by setting them false then you treat them as
// 'good' if you wish - whatever
$checkedGoodToys = array();
$checkedBadToys = array();
//obtain the database object on a row by row basis
foreach($allToys as $oneToy)
{
if (isBadToy($oneToy)) {
// do what you want with the bad toy...
$checkedBadToys[] = $oneToy;
}
else {
// do what you want with the good toy...
$checkedGoodToys[] = $oneToy;
}
}
var_dump($checkedGoodToys, 'The Good Toys');
var_dump($checkedBadToys, 'The Bad Toys');
exit;
// check if the toy is in the badToy array
function isBadToy($theToy)
{
global $badToys;
return isset($badToys[$theToy]) && $badToys[$theToy];
}
in_array()做到了。谢谢你的回答。
database objects containing ("Volvo","BMW","Toyota"); //assume that this is a continous stream of data from a database where we don't know the total elements. Just that single element
$toys=array("BMW","Toyota"); //assume that this is a list of blacklisted users
for($rindex=0; $rindex < count($cars); $rindex++)
{
for($index=0; $index < size(database objects); $index++)
{
//obtain the database object on a row by row basis
if (in_array($cars[$rindex] , $toys) //specify exclusion
{
echo $cars[$rindex];
}
}
}