有没有更快的方法来检查null
php多维数组的一列中数字(不是)的存在(例如number9
)?
在if statement
下面似乎是工作好。
$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)
这是我的想法。
首先是仅过滤数组中的仅数字值,然后将其与原始值进行比较:
function with_array_filter($arr) {
return $arr == array_filter($arr, 'is_numeric');
}
第二个示例使用强制转换为浮点数然后返回字符串的方式,请记住,这对于很大的数字来说并不准确,但是似乎是最快的(如果您真的很在意):
function is_numeric_array_with_cast($arr) {
foreach ($arr as $b) {
if ($b != (string)(float)$b) {
return false;
}
}
return true;
}
但是,可能最简单的解决方案是foreach
将数组仅放在函数内部并尽早返回:
function is_numeric_array_with_func($arr) {
foreach ($arr as $b) {
if (!is_numeric($b)) {
return false;
}
}
return true;
}
在PHP 7.2上以20个元素组成的数组进行了100000次迭代的基准测试:
$falseArray = [
'1',
2.5,
-10,
32,
11.0,
2.5,
100101221,
345,
-10,
'-10',
'+10',
'10',
12,
PHP_INT_MAX,
PHP_INT_MAX + 1.4e5,
'-10',
null,
'a',
'5',
5
];
Matt Fryer
Time: 4.8473789691925
is_numeric_array_with_func
Time: 4.0416791439056
is_numeric_array_with_cast
Time: 3.2953300476074
with_array_filter
Time: 3.99729180336
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句