简体   繁体   English

检查多维数组键的所有值是否都是数字?

[英]Check if all values of keys of multidimentionnal array are numeric?

i'm gona crazy, debuting in php.. 我快疯了,首次亮相php ..

I need to check if key value of an multidimentionnal array are all numeric.. 我需要检查多维数组的键值是否都是数字。

a print_r() of my $values_arr give that: 我$ values_arr的print_r()给出:

Array ( [coco] => Array ( [0] => 18 [1] => 99 ) [chanel] => 150

I need to check if 18 and 99 and 150 are numeric, i will don't know what will in the array , and this array will not more 2 dimention. 我需要检查18和99和150是否为数字,我将不知道数组中的内容,并且该数组将不会再有2维。

I tryed many things, the last one..: 我尝试了很多事情,最后一件..:

foreach ( $values_arr as $foo=>$bar ) { 

 if(  !in_array( $foo, $_fields_arr )  || !is_numeric($bar ) ) {

                        echo "NOTGOOD";   

                 } 
                 }




                          ****UPDATE****

new test :Here because chanel isnot int , this exemple should be echo "not goud", but its not the case.. 新测试:在这里,因为香奈儿不是int,因此该示例应回显为“ not goud”,但事实并非如此。

$_fields_arr = array('coco','chanel','other');                                

$ary = array(
  'coco' => array(18, 99),
  'chanel' => 'yu'
);


function allIntValues($o)
{
  if (is_int($o)) return true;
  if (is_array($o)){
    foreach ($o as $k => $v) {
      if (!is_int($v)) return false;
    }
  }
  return true;
}

foreach ($ary as $k => $v) {
  if (!in_array($k, $_fields_arr) || !@allIntValues($v)){

echo "notgood";

 }

  else echo "good";
}

thanks for any help, regards 感谢您的任何帮助,问候

Update: 更新:

$ary = Array(
  'coco' => array(18, 99),
  'chanel' => 150
);
$_fields_arr = array('coco', 'chanel');

function allIntValues($o)
{
  if (is_int($o)) return true;
  if (is_array($o)){
    foreach ($o as $k => $v) {
      if (!is_int($v)) return false;
    }
  }
  return true;
}

foreach ($ary as $k => $v) {
  if (in_array($k, $_fields_arr) && @allIntValues($v)){
    // $ary[$k] is no good
  }
}

Assuming you want to test if all values are numeric (despite how deep the value's nested): 假设您要测试所有值是否都是数字(尽管值嵌套的深度):

function is_numeric_array($ary)
{
  foreach ($ary as $k => $v)
  {
    if (is_array($v))
    {
      if (!is_numeric_array($v))
        return false;
    }
    else if (!is_numeric($v))
      return false;
  }
  return true;
}

That will (recursively) check the array and make sure every value is numeric within the array. 这将(递归)检查数组并确保数组中的每个值都是数字。

array(1,2,3) // true
array('foo','bar','baz') // false ('foo', 'bar' & 'baz')
array(1,2,array(3,4)) // true
array(array(1,'foo'),2,3) // false (foo)
array("1,", "2.0", "+0123.45e6") // true

您正在使用值而不是键:

if(  !in_array( $bar, $_fields_arr )  || !is_numeric($foo ) ) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM