douxian7808 2019-04-06 20:50
浏览 48

如果条件动态创建PHP

I have a form with multiple fields a user can search by. How do I dynamically write the if condition based on the fields selected by user?

E.g. I have 3 fields as follows:

$categoryId = $_REQUEST['category_id'];
$locationId = $_REQUEST['location_id'];
$statusId = $_REQUEST['status_id'];

If the user selected category_id and location_id and status_id then my if statement would be should be as follows:

if (!empty($categoryId) && !empty($locationId) && !empty($statusId)) {
  if (isInTaxonomy($recordId, $categoryId) && isInTaxonomy($recordId, $locationId) && isInTaxonomy($recordId, $statusId) {
    // Do something
  }
}

if the user selected category_id and location_id then my if statmeent would be as follows:

if (!empty($categoryId) && !empty($locationId)) {
  if (isInTaxonomy($recordId, $categoryId) && isInTaxonomy($recordId, $locationId) {
    // Do something
  }
}

if the user only selected category_id then my if statmeent would be as follows:

if (!empty($categoryId)) {
  if (isInTaxonomy($recordId, $categoryId)) {
    // Do something
  }
}

As you can see I'm having to implement every possible combination of fields a user can select to build all the different conditions.

I was thinking of doing something like the following but that just give me a string and I don't want to use eval to execute it:

$filter = [(!empty($categoryId) ? '(isInTaxonomy($recordId, $categoryId))' : ''),
         (!empty($locationId) ? '(isInTaxonomy($recordId, $locationId))' : '')];

$condition = implode(' && ', array_filter($filter));

if (eval("return $condition;")) {
   // Do something
}

Is there a way to dynamically generate all the condition using more concise code without having to resort to Eval?

  • 写回答

3条回答 默认 最新

  • douyi5157 2019-04-06 21:03
    关注

    I presume you can use the following approach - define available keys and iterate over them, while iterate - collect some data, for example like this:

    $keys = ['category_id', 'location_id', 'status_id'];
    
    $operationAllowed = true;
    foreach ($keys as $key) {
        if (!empty($_REQUEST[$key])) {
            $operationAllowed = $operationAllowed && isInTaxonomy($recordId, $_REQUEST[$key]);
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器