一个数据组的筛选器:对一个二维母数组$motherArr,经过一个由N条苛刻条件组成的筛选器的筛选,获取到进入筛选器数据组成的子数组$sonFirArr和筛选器外的数据组成的子数组$sonSecArr,然后随机从子数组$sonFirArr中取出(count($sonFirArr)*m%)个元素,得到孙数组$grandsonFirArr,进一步获取母数组$motherArr中对孙数组$grandsonFirArr的互补孙数组$grandsoSecArr,即孙数组$grandsonFirArr和孙数组$grandsoSecArr为我们需要的结果。
具体处理如下:
1,遍历母数组$motherArr,筛选器外的记录放入一个新数组(子数组$sonFirArr),同时对母数组unset()该条记录(生成子数组$sonSecArr)
if($sellerParent || $buyerParent){
$orderArr[$i] = $order;
unset($orders[$i]);
continue;
}
if($sellerSpreadCount <= 10 || $buyerSpreadCount <= 10){
$orderArr[$i] = $order;
unset($orders[$i]);
continue;
}
if($order['spreadseller'] > 3 || $order['spread'] > 3){
$orderArr[$i] = $order;
unset($orders[$i]);
continue;
}
注意:筛选条件中存在一个前10条的筛选,而此10条的记录是在筛选后的筛选器外的结果遍历时产生的,如果从对应的表里查询是不可取的;如果采用缓存记录条数,也不可以放在筛选器外的结果遍历时;因为如果10条的界点正好在筛选后执行的遍历时,同时其内出现了符合筛选条件的11,12等条。所以我在筛选遍历时对符合产生“前10条”的记录进行缓存记录数值
if ($order['spread']>0 && isset($userRelations[$bid])) {
$userRelation = $userRelations[$bid];
$parentid = $userRelation['parentid'];
$buyerSpreadCount = $this->xmcache->get("spread_".$userRelation['id']);
if($buyerSpreadCount){
$this->xmcache->setEx("spread_".$userRelation['id'],3600*24*30*6,$buyerSpreadCount+1);
}else{
$this->xmcache->setEx("spread_".$userRelation['id'],3600*24*30*6,1);
}
if(in_array($parentid, $whiteUserArr)){
$buyerParent = true;
}
}
这里我想说,遍历内,如果取固定字段的另一组信息,这样设置:将二维数组的索引设为改固定字段值,如上文对$userRelations的处理。
2,编写随机获取某一数组的一定数量的元素,这个方法里主要通过随机获取数组索引方式从而达到需求,当然您还可以尝试打乱数组的方式:shuffle()
注意:没被随机选中的元素也被返回了
private function getRandElements($array = array(), $ratio){
if(empty($array) || !is_array($array)){
return array('deductResult'=>array(),'resultArr'=>array());
}
if (!$ratio) {
return array('deductResult'=>array(),'resultArr'=> $array);
}
$key = array_rand($array,ceil(count($array)*$ratio));
if(!is_array($key)){
$key = [$key];
}
$deductResult = $resultArr = array();
foreach($key as $val){
$deductResult[] = $array[$val];
}
foreach ($array as $k => $v) {
if(!in_array($k,$key)){
$resultArr[$k] = $v;
}
}
return array('deductResult'=>$deductResult,'resultArr'=>$resultArr);
}
3,上步获取到$grandsonFirArr即最终的筛选器结果,如何获取母数组$motherArr中对孙数组$grandsonFirArr的互补孙数组$grandsoSecArr?我们记得步1中的筛选外的数组$orderArr和步2中随机外的部分$resultArr,如果合并两者是不是就可以了?
$newOrderArr = array_merge($orderArr,$returnRes['resultArr']);
即$grandsonSecArr。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。