如何根据特定类别对数组值进行分组

时间:2011-11-10 13:16:58

标签: php mysql arrays

多个选择选项的数组输出

Array
(
    [q] => Array
        (
            [0] => monkey
            [1] => pig
            [2] => dog
            [3] => banana
            [4] => apple
            [5] => mango
            [6] => lavender
            [7] => magnolia
            [8] => marigold

        )

)

代码

$queryArray  = array_map("secure", $_GET['q']);
$inArray     = array();

foreach ($queryArray as $key) {
    $inArray[] = 'animals="' . $key . '"';
}

$sql = 'SELECT * FROM kids WHERE ' . implode(' AND ', $inArray) . '';
echo $sql;

问题:

如何将当前数组分组为

animals = monkey,pig,dog
fruits  = banana,apple,mango
flowers = lavender,magnolia, marigold

也许手动过滤价值或in_array monkey,pig,dog是动物。

并制作正确的MySQL语句以获得类似的内容

SELECT * 
FROM kids 
  WHERE 
   (animals="monkey" OR animals="pig" OR animals="dog")
AND 
   (fruits="banana" OR fruits="apple" OR fruits="mango") 
AND 
   (flowers="lavender" OR flowers="magnolia" OR flowers="marigold")

让我知道。

1 个答案:

答案 0 :(得分:0)

您可以使用PHP关联数组来存储查询,如下所示:

$inArray['animals'] = SELECT * FROM kids WHERE 
                      (animals="monkey" OR animals="pig" OR animals="dog")

$inArray['fruits']  = SELECT * FROM kids WHERE
                      (fruits="banana" OR fruits="apple" OR fruits="mango") 

$inArray['flowers'] = SELECT * FROM kids WHERE
                     (flowers="lavender" OR flowers="magnolia" OR flowers="marigold")