首页 > 解决方案 > Fastest return TRUE if all values of a column of a multidimensional array is_numeric

问题描述

Are there faster methods to check the existence of a number (not null) in one column of a multidimensional array in php (for instance, number9)?

Attempt:

The if statement below seems to be working okay.

$arr=Array(
    [0] => Array
        (
            [date] => 2019-01-16
            [number1] => 20.4
            [number2] => 20.54
            [number3] => 19.71
            [number4] => 19.73
            [number5] => 70849266
            [number6] => 70849266
            [number7] => -0.65
            [number8] => -3.189
            [number9] => 20.0902
            [string1] => Jan 16
            [number10] => 0.047796070100903
        )

    .
    .
    .

    [21] => Array
        (
            [date] => 2019-01-17
            [number1 => 19.49
            [number2] => 20.51
            [number3] => 19.02
            [number4] => 20.25
            [number5] => 85018421
            [number6] => 85018421
            [number7] => 0.52
            [number8] => 2.636
            [number9] => 19.7988
            [string1] => Jan 17
            [number10] => 0.075411577270313
        )

);


function isNumeric($var){
  if (is_numeric($var)){
    return true;
  } else {
    return false;
  }
}


if((array_walk(array_column($arr, "number8"), 'isNumeric'))!=1)

标签: phparraysmultidimensional-arraynullnumbers

解决方案


感谢大家,感谢您的精彩回答!

在我的 PC 上,我在 PHP 5.5.38 中尝试了您的四个函数,迭代次数约为 5000 次,总时间为:

"is_numeric_array_with_cast total time is 0.44153618812561"
"with_array_filter total time is 0.21628260612488"
"is_numeric_array_with_func total time is 0.14269280433655"
"is_numeric_matt_fryer total time is 0.155033826828"


$t1=$t2=$t3=$t4=0;
foreach($arrs as $k=>$arr){
    $s1=microtime(true);
    is_numeric_array_with_cast(array_column($arr, "number8"));
    $e1=microtime(true)-$s1;
    $t1=$t1+$e1;

    $s2=microtime(true);
    with_array_filter(array_column($arr, "number8"));
    $e2=microtime(true)-$s2;
    $t2=$t2+$e2;


    $s3=microtime(true);
    is_numeric_array_with_func(array_column($arr, "number8"));
    $e3=microtime(true)-$s3;
    $t3=$t3+$e3;

    $s4=microtime(true);
    is_numeric_matt_fryer(array_column($arr, "number8"),"number8");
    $e4=microtime(true)-$s4;
    $t4=$t4+$e4;

}






function is_numeric_array_with_cast($arr) {
    foreach ($arr as $b) {
        if ($b != (string)(float)$b) {
            return false;
        }
    }
    return true;
}


function with_array_filter($arr) {
    return $arr == array_filter($arr, 'is_numeric');
}


function is_numeric_array_with_func($arr) {
    foreach ($arr as $b) {
        if (!is_numeric($b)) {
            return false;
        }
    }
    return true;
}

function is_numeric_matt_fryer($arr,$str){
  $bool = true;
  foreach ($arr as $row)
  {
      if (!is_numeric($row[$str]))
      {
          $bool = false;
      }
  }
  return $bool;
}

推荐阅读