1

试图遍历 php 中的查询字符串,但只获取最后一个值。我应该怎么做才能获得所有值?

例如:querystring = ?style=ranch&style=barn&style=colonial

php:

$sqlStyle = "SELECT DISTINCT COUNT(*) as count  FROM houses_single ";
$i = 1;
foreach ($_GET as $key => $value) {
    if ($i == 1){
        $sqlStyle .= "where ";
     }else{
        $sqlStyle .= " and ";
    }
    $sqlStyle .=  $key . " like '%" . $value ."%'";
    $i++;
 }
 echo $sqlStyle;

结果:SELECT DISTINCT COUNT(*) as count FROM house_single Where Houses like '%colonial%'

4

1 回答 1

1

在这种情况下,查询参数“style”是一个数组,必须用方括号标识 - 如果不是,最后一个 key=value 对将覆盖其他对。

?style[]=ranch&style[]=barn&style[]=colonial

$_GET['style']是一个数组,那么你可以通过使用循环foreach

foreach ($_GET['style'] as $value) {
    // ...
}

如果 'style' 不是您要添加的唯一参数,您可以在循环中使用is_array()检查:foreach

    foreach ($_GET as $key => $value) {
        if ($i == 1){
            $sqlStyle .= "where ";
         }else{
            $sqlStyle .= " and ";
         }

         if(is_array($value)) {
             $sec = array();
             foreach($value as $second_level) {
                 $sec[] =  $key . " LIKE '%" . $second_level."%'";
             }
             $sqlStyle .= implode(' AND ', $sec);
         }
         else {
            $sqlStyle .=  $key . " LIKE '%" . $value ."%'";
         }

         $i++;
     }
     echo $sqlStyle;

没有 foreach 的替代方案:

<?php

$statement = "SELECT DISTINCT COUNT(*) as count FROM `houses_single`";

if(is_array($_GET)) {
   $statement .= ' WHERE';

   // create copy to keep the $_GET array
   $add_where = $_GET;

   array_walk(function($elem,$key){
      is_array($elem) {
         return implode(' AND ', array_map(function($sec) using ($key)  {
             return "$key LIKE '%$sec%'";
         }, $elem);
      }
      else {
            return "$key LIKE '%$elem%'";
      }
   },$add_where);

   $statement .= implode(' AND ', $add_where);
}

(代码未经测试)

Sidenode 关于安全性:我希望您不会在没有任何参数转义的情况下使用您在生产环境中提供的这段代码片段。

于 2013-03-03T00:41:47.333 回答