我有陣列過濾多維數組
$rows = [
['k'=>1, 'dop1'=>'take', 'dop2' => 'a', 'dat' => '25-11-2016'],
['k'=>2, 'dop1'=>'make', 'dop2' => 'b', 'dat' => '26-11-2016'],
['k'=>3, 'dop1'=>'sake', 'dop2' => 'c', 'dat' => '27-11-2016'],
['k'=>4, 'dop1'=>'bake', 'dop2' => 'd', 'dat' => '28-11-2016'],
['k'=>5, 'dop1'=>'dake', 'dop2' => 'e', 'dat' => '29-11-2016'],
['k'=>6, 'dop1'=>'jake', 'dop2' => 'f', 'dat' => '30-11-2016'],
['k'=>7, 'dop1'=>'ake', 'dop2' => 'g', 'dat' => '24-11-2016']
];
和另一個數組用於過濾
$filters = [
['dat', '=', '27-11-2016'],
['dop1', '=', "bake"],
['dop1', '=', "sake"],
['dop1', '=', "take"],
];
如果重複陣列濾光器的第一個元素,將它們之間OR
表達,否則將是AND
表達式。 所以這裏的結果必須是['k'=>3, 'dop1'=>'sake', 'dop2' => 'c', 'dat' => '27-11-2016']
,因爲'dat' => '27-11-2016'
存在於filters數組中,並且'dop1'=>'sake''dop1'=>'sake'
也存在。你能幫我嗎?
UPDATE 這是我的代碼示例,但在註釋的位置存在問題。
$dop = ['dop1', 'dop2', 'dop3', 'dop4'];
$result = [];
foreach ($rows as $row) {
foreach ($filters as $filter) {
if(in_array($filter[0], $dop)){
$new_filter = [];
$f = explode("\n", $filter[2]);
foreach ($f as $item) {
array_push($new_filter, [$filter[0], $filter[1], $item]);
}
if(count($result) == 0){
foreach ($new_filter as $new) {
if($row[$new[0]] == $new[2]){
array_push($result, ['r' => $row, 'filter' => $new, 'validity' => 'valid']);
}
}
} else {
foreach ($new_filter as $new) {
for($i=0;$i<count($result);$i++){
if($result[$i]['filter'][0] == $new[0] && $result[$i]['filter'][1] == $new[1] && $result[$i]['filter'][2] != $new[2]){
//array_push($result, ['r' => $row, 'filter' => $new, 'validity' => 'valid']);
}
}
}
$invalid = 1;
$id = 0;
foreach ($new_filter as $new) {
for($i=0;$i<count($result);$i++){
if($result[$i]['r'][$new[0]] == $new[2]){
$invalid = 0;
$id = $i;
break 2;
}
}
}
if($invalid == 1){
$result[$id]['validity'] = 'invalid';
}
}
} elseif($filter[0] == 'dat') {
if(count($result) == 0){
if($row[$filter[0]] == $filter[2]){
array_push($result, ['r' => $row, 'filter' => $filter, 'validity' => 'valid']);
}
} else {
if($row[$filter[0]] == $filter[2]){
for($i=0;$i<count($result);$i++){
if($result[$i]['r'][$filter[0]] != $filter[2]){
$result[$i]['validity'] = 'invalid';
}
}
}
}
}
}
}
$c = 0;
foreach ($result as $r) {
if($r['validity'] == 'valid'){
$c++;
}
}
echo $c;
你可以再試一次來說明OR和AND部分......我不完全相信我明白了。你的例子預期的結果是好的......但請澄清當你是或當你是和。 – WEBjuju
我不能發現你自己的嘗試,所以你自己的代碼來實現這一點。你如何期待我們幫助?請注意,我們在這裏幫助您編寫代碼,而不是爲您編寫代碼。爲此,請聘請付費程序員。 – arkascha
@arkascha抱歉,忘記了我自己的代碼,我更新了問題,請幫助我。 –