dongnuochen9449 2014-10-01 03:25
浏览 33
已采纳

PHP帮助从函数中检索结果时简化IF语句

Let's say i have this function that seeks for a value inside a bidimensional array:

function findValueBi($array, $field, $value, $returnfield)
{
   foreach($array as $key => $product)
   {
      if ( $product[$field] === $value )
         return $product[$returnfield];
   }
   return false;
}

And the bidimensional array looks like this:

Array
(
    [0] => Array
        (
            [number] => 2
            [type] => unimodal
        )

    [1] => Array
        (
            [number] => 6
            [type] => unimodal
        )

    [2] => Array
        (
            [number] => 8
            [type] => multimodal
        )

    [3] => Array
        (
            [number] => 27
            [type] => multimodal
        )

    [4] => Array
        (
            [number] => 29
            [type] => multimodal
        )
)

What the function does, is to look for a given value inside the 'number' key. If it's found, i retrieve its corresponding 'type' key value. For example, if i am looking for the 'number' 29, then i will get the 'type' value "multimodal" (the last item of the array sample). Otherwise, if the value is not found, the function returns false.

So, the way i retrieve this value is as follows:

if(findValueBi($numbers_patterns,'number',$number,'type')!==false){
                $resultado=findValueBi($numbers_patterns,'number',$number,'type');
                return $resultado;
            }
else{ ... }

Is there a better and/or faster way to do this? Is it possible to retrieve the info right inside the if statement? As you can see, I am calling the function twice, so how can i call it once with the if statement???

  • 写回答

1条回答 默认 最新

  • dpx49470 2014-10-01 03:28
    关注

    You could just elect to use it the first time, then use it inside the if:

    $resultado = findValueBi($numbers_patterns,'number',$number,'type'); // call it once
    if($resultado !== false){
        // use $resultado here 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数