doucan8276 2017-05-06 10:39
浏览 101
已采纳

如何使用分隔的列和值数组生成查询

I have this array:

$filter=['color*black','color*blue','color*red','paint*apex','paint*dalton'];

Each value in $filter has two substrings separated by *. The first substring represents a database table column and the second represents a desired value for that column.

My products table looks like this:

id    name    color    paint
1     p1      black     compo
2     p2      red       dalton
3     p3      pink      apex
4     p4      blue      apex
5     p5      cream     compo

Using $filter, I need to search the products table and return all rows with a paint value of apex or dalton AND a color value of black, blue, or red.

The desired output is a mysql query that will only return these rows:

id    name    color    paint
2     p2      red       dalton
4     p4      blue      apex
  • 写回答

2条回答 默认 最新

  • duanji4449 2017-05-06 11:02
    关注

    If You need to construct a query like this SELECT * FROM products WHERE (color IN ('black', 'blue', 'red')) AND (paint IN ('apex', 'dalton')), then the code below might be useful (please, check it here):

    $filter = array(
        0 => "color*black",
        1 => "color*blue",
        2 => "color*red",
        3 => "paint*apex",
        4 => "paint*dalton"
    );
    
    $elements = [];
    
    foreach ($filter as $value) {
        list($before, $after) = explode('*', $value);
        $elements[$before][] = $after;
    }
    
    $parts = [];
    
    foreach ($elements as $column => $values) {
        $parts[] = "(`$column` IN ('" . implode("', '", $values) . "'))";
    }
    
    $query = 'SELECT * FROM `products` WHERE ' . implode(' AND ', $parts);
    

    Running this query against the given table data structure:

    id    name    color    paint
    1     p1      black     compo
    2     p2      red       dalton
    3     p3      pink      apex
    4     p4      blue      apex
    5     p5      cream     compo
    

    will match the following rows:

    2     p2      red       dalton
    4     p4      blue      apex
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题