编辑PHP JSON数组值

时间:2014-08-28 12:50:48

标签: php json

我有一个ajax系统,可以过滤客户网站的结果。

我们正在为"场地类型"实施过滤器。每个复选框的名称为:venuetype [typeHere]。

现在很明显这会像那样传递给PHP,但我感兴趣的是typeHere部分。

我需要检查venuetype是否在数组中,如果是,则删除venuetype []并保留typeHere。

我的PHP脚本如下:

$select = 'SELECT *'; 
$from = ' FROM venues'; 
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');

if (in_array("nocorkage", $opts)){
 $where .= " AND nocorkage = 1";
}

if (in_array("hotel", $opts)){
 $where .= " AND hotel = 1";
}

if (in_array("selfcatering", $opts)){
 $where .= " AND selfcatering = 1";
}

if (in_array("marquees", $opts)){
 $where .= " AND marquees = 1";
}
if (in_array("inhousecatering", $opts)){
 $where .= " AND inhousecatering = 1";
}
if (in_array("outsidecatering", $opts)){
 $where .= " AND outsidecatering = 1";
}
if (in_array("licensed", $opts)){
 $where .= " AND licensed = 1";
}
if (in_array("venuetype", $opts)){
 // Function to go here
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
while($output = $statement->fetch(PDO::FETCH_ASSOC))
{
   $return[]=array('id'=>$output['id'],
                'title'=>$output['title'],
                'main_image'=>$output['main_image']);
}
$json = json_encode($return);
echo($json);
?>

有人可以让我知道我需要做什么,我在想PHP正则表达式......这样就够了吗?

2 个答案:

答案 0 :(得分:1)

lil bit off-topic

我会像

一样创建我的代码
function setWhere($array,$opts,&$where){
    foreach($array as $arr){
        if(in_array($arr,$opts))
            $where .= " AND {$arr} = 1"; 
    }
}

$wAarray = array("nocorkage", 
                 "hotel", 
                 "selfcatering", 
                 "marquees", 
                 "inhousecatering", 
                 "outsidecatering", 
                 "licensed");

setWhere($wArray, $opts, $where);

//... more if your code

而不是X if语句

<强>说明: 问题是:为什么$ where有&符号?

它是对变量的引用

示例:

$foo  = "hello";
$bar  = "world";
function doSomething($str){
    return $str;
}
echo $bar;  //outputs: world
$bar = doSomething($foo);
echo $bar;  //outputs: hello

与参考相同

$foo  = "hello";
$bar  = "world";
function doSomething(&$str){
    $str = $foo;
}

echo $bar; //outputs: world
doSomething($bar);
echo $bar; //outputs: hello

答案 1 :(得分:0)

不完全确定这是您所需要的,但如果您使用:

foreach($opts["venuetype"] as $typeHere => $venuetype){

    // $typeHere will iterate all the key names in the venuetype array

}