【发布时间】:2013-02-27 02:58:49
【问题描述】:
我有这样的Array:
array(10) { [0]=> object(stdClass)#3 (4) { ["name"]=> string(2) "OA" ["datetime"]=> string(10) "1990-05-10" ["amount"]=> string(2) "50" ["comment"]=> string(9) "Something" } [1]=> object(stdClass)#4 (4) { ["name"]=> string(1) "O" ["datetime"]=> string(10) "1992-10-01" ["amount"]=> string(2) "20" ["comment"]=> string(5) "Other" } ...
我将使用 php 在标记的数组中搜索信息。我有一个HTML 表单,其中包括许多过滤器(所有参数都在该数组中定义)。所以这是我的 php 脚本:
if (isset($_POST['action'])){ // if form is submitted
$name = $_POST['name'];
$amount = $_POST['amount'];
// like I've mentioned I've more filters but to simplify example lets have two
if ($name!="" && $amount!=""){ // search by both param
foreach($arr as $obj){ // $arr is the marked array from above
if ( (strpos(strtolower($obj->name),strtolower($name))!==false) && ($amount >= $obj->amount) ){
$new[] = (object)array(
"name" => $obj->name,
"datetime" => $obj->datetime,
"amount" => $obj->amount,
"comment" => $obj->comment
);
}
}
print_r($new);
} elseif ($name=="" && $amount!=""){ // only by amount
// same foreach loop goes here with difference that I'm only searching by amount
} elseif ($name!="" && $amount==""){ // only by name
// same foreach loop goes here with difference that I'm only searching by name
}
// etc ...
}
一切正常,但我只是对缩短这么多 if 语句并实现目标的另一种简单方法感兴趣。感谢您的建议...
【问题讨论】: