<?php
namespace org;
class Search{
private $source;
public function __construct($source=[]) {
$this->source=$source;
return $this;
}
public function where($condition,$retain=false) {
$recode=[];
foreach ($this->source as $sourcekey=>$sourceVo) {
$state=true;
foreach ($condition as $conditionVo){
$row=$this->arraySeek($sourceVo,$conditionVo[0]);
if($conditionVo[1]=='='){
$row==$conditionVo[2]||($state=false);
}elseif($conditionVo[1]=='<>'){
$row==$conditionVo[2]&&($state=false);
}elseif($conditionVo[1]=='in'){
in_array($row,$conditionVo[2])||($state=false);
}elseif($conditionVo[1]=='like'){
strstr($row,$conditionVo[2])==false&&($state=false);
}elseif($conditionVo[1]=='between'){
($row>=$conditionVo[2][0] && $row<=$conditionVo[2][1])||($state=false);
}else{
die('匹配规则失败!');
}
}
if($state){
$retain&&$sourceVo['rowKey']=$sourcekey;
$recode[]=$sourceVo;
}
}
$this->source=$recode;
return $this;
}
public function loop($fun){
foreach ($this->source as $key=>$vo) {
$this->source[$key]=$fun($vo,$key);
}
return $this;
}
public function find() {
return empty($this->source)?[]:$this->source[0];
}
public function select() {
return $this->source;
}
public function count() {
return count($this->source);
}
private function arraySeek($data,$rule){
$recode=$data;
is_array($rule)||($rule=explode('|',$rule));
foreach ($rule as $ruleVo) {
if(is_array($recode) && isset($recode[$ruleVo])){
$recode=$recode[$ruleVo];
}else{
$recode='';
break;
}
}
return $recode;
}
}