在数组中搜索数字

时间:2012-02-08 14:55:50

标签: php arrays search

$record_record包含:

Array
(
    [0] => Array
        (
            [id] => 252
            [origin] => laptop.me.
        )

    [1] => Array
        (
            [id] => 255
            [origin] => hello.me.
        )

    [2] => Array
        (
            [id] => 254
            [origin] => intel.me.
        ) 
)

我需要搜索数组中是否存在255。下面的代码不起作用。

if (in_array('255', $record_record, true)) {
    echo "'255' found with strict check\n";
}
else {
     echo "nope\n";
} 

我有一种感觉,因为它是一个嵌套数组,该函数无法正常工作。请帮帮我?

5 个答案:

答案 0 :(得分:2)

做类似的事情:

 foreach($record_record as $sub_array){
        if (in_array('255', $sub_array, true)) {
           echo "'255' found with strict check\n";
        }
       else {
           echo "nope\n";
        } 
    }

答案 1 :(得分:2)

你需要做这样的事情:

<?php

  function id_exists ($array, $id, $strict = FALSE) {
    // Loop outer array
    foreach ($array as $inner) {
      // Make sure id is set, and compare it to the search value
      if (isset($inner['id']) && (($strict) ? $inner['id'] === $id : $inner['id'] == $id)) {
        // We found it
        return TRUE;
      }
    }
    // We didn't find it
    return FALSE;
  }

  if (id_exists($record_record, 255, true)) {
    echo "'255' found with strict check\n";
  } else {
    echo "nope\n";
  } 

答案 2 :(得分:1)

你需要一个递归函数。来自elusive

 function in_array_r($needle, $haystack, $strict = true) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

或者,如果您的数组结构永远不会改变,只需编写一个简单的循环:

function in_2dimensional_array($needle, $haystack, $strict = true){
   foreach ($haystack as $item) {
       if (in_array($needle, $haystack, true)) {
           return true;
       }
   }

   return false;
}

答案 3 :(得分:0)

Hacky解决方案。其他人会使用array_map或类似的东西发布一个很好的。

function in_nested_array($val, $arr)
{
    $matched = false;
    foreach ($arr AS $ar)
    {
        if (in_array($val, $ar, true)
        {
            $matched = true;
            break;
        }
    }
    return $matched;
}

if (in_nested_array(255, $record_record))
{
    // partay
}

答案 4 :(得分:0)

<?php
foreach($record_record as $record) {
  $key = array_search('255', $record);
  if ($key) {
     echo "'255' found with strict check\n";
  }
}
?>