string(2) "OA" ["datetime"]=> s-6ren">
gpt4 book ai didi

php - 在数组 php 中搜索信息时缩短脚本

转载 作者:搜寻专家 更新时间:2023-10-31 20:44:08 24 4
gpt4 key购买 nike

我的 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 语句并实现目标的简单方法感兴趣。感谢您的建议...

最佳答案

它当然看起来并不短,但那是因为您省略了其他 foreach 循环。这是第一次重构你的东西,没有重复的代码:

        $arr = arrayThing();
$new = array();
if (isset($_POST['action']))
{ // if form is submitted
$name = isset($_POST['name']) ? $_POST['name'] : '';
$amount = isset($_POST['amount']) ? $_POST['amount'] : '';
if ($name != '' && $amount != '')
{
$searchBy = 'both';
}
elseif ($name == '' && $amount != '')
{
$searchBy = 'amount';
}
else
{
$searchBy = 'name';
}

foreach ($arr as $obj)
{
$valid = false;
switch ($searchBy)
{
case 'both':
if ((strpos(strtolower($obj->name), strtolower($name)) !== false) && ($amount >= $obj->amount))
{
$valid = true;
}
break;
case 'amount':
if ($amount >= $obj->amount)
{
$valid = true;
}
break;
case 'name':
if (strpos(strtolower($obj->name), strtolower($name)) !== false)
{
$valid = true;
}
break;
default:
break;
}

if ($valid)
{
$new[] = (object) array(
"name" => $obj->name,
"datetime" => $obj->datetime,
"amount" => $obj->amount,
"comment" => $obj->comment,
);
}
}
print_r($new);
}

关于php - 在数组 php 中搜索信息时缩短脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15346965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com