我有一个循环中的数据流。这将从数据库中逐行检索结果。但是,我希望在流和给定数组之间设置一种数组差异形式。给定的数组是一个排除列表,例如黑名单上的用户列表。到目前为止,这就是我所拥有的。
这是一个虚构的例子。我不想写所有数据库代码逐行检索结果
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提供答案。
发布于 2014-03-31 09:58:30
快速查找数组--对代码进行注释和测试。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];
}发布于 2014-03-31 16:44:42
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];
}
}
}https://stackoverflow.com/questions/22754093
复制相似问题