我怎样才能简化这个数组,使MySQL成为条件

时间:2018-02-21 10:20:12

标签: php mysql

Array (
    [0] => Array ( [ram] => 2 GB )
    [1] => Array ( [ram] => 4 GB )
    [2] => Array ( [ram] => 6 GB )
    [3] => Array ( [screen_size] => 5 - 6 Inch )
    [4] => Array ( [screen_size] => 6 - 7 Inch )
    [5] => Array ( [network_connectivity] => 3G )
    [6] => Array ( [network_connectivity] => 4G )
)

如何简化在mysql where子句中使用的数组??? 例如=

从表中选择*(ram ='2GB'或ram ='4GB')和(screen_size ='5 - 6英寸'或screen_size ='6 - 7英寸')和(network_connectivity ='3G'或network_connectivity ='4G')

我试过了

$condition = "";
if(!empty($this->input->post('datafilter'))){
foreach ($this->input->post('datafilter') as $mainfilter) {
  foreach ($mainfilter as $key => $value) {
   //echo $condition.'<br>';
   if(!empty($condition)){
    if (strpos($condition, $key) === true) {
       $con = ' AND ';
    } else {
      $con = ' OR ';
    }
    }
    else{
      $con = ' OR ';
    }
    $condition .= $key.' = '.$value . $con;
  }
}
}

结果是: ram = 2 GB或ram = 4 GB或ram = 6 GB或screen_size = 5 - 6英寸或screen_size = 6 - 7英寸或network_connectivity = 3G或network_connectivity = 4G或

1 个答案:

答案 0 :(得分:0)

我在PHP中的表现不是很好(我是Perl程序员),但这段代码似乎按预期工作:

<?php
    $optList=[
        [ 'ram' => '2 GB' ],
        [ 'ram' => '4 GB' ],
        [ 'ram' => '6 GB' ],
        [ 'screen_size' => '5 - 6 Inch' ],
        [ 'screen_size' => '6 - 7 Inch' ],
        [ 'network_connectivity' => '3G' ],
        [ 'network_connectivity' => '4G' ]
    ];
    $optByItems=[];
    foreach ($optList as $opts) {
        foreach ($opts as $item => $value) {
            $optByItems[$item][$value]=1;
        }
    }
    $query='';
    foreach ($optByItems as $item => $values) {
        $query .= (empty($query) ? '' : ' AND ') . "($item='" . join("' OR $item='", array_keys($values)) . "')";
    }
    echo $query;
?>