【问题标题】:How to use PHP in_array with associative array?如何将 PHP in_array 与关联数组一起使用?
【发布时间】:2014-03-15 13:41:39
【问题描述】:

你通过mysql函数“mysql_fetch assoc”得到的关联数组有没有什么php函数比如in_array?

例如,如果我有一个如下所示的 $array:

array(0=>(array(ID=>1, name=>"Smith"), 1=>(array(ID=>2, name=>"John"))

我可以做类似in_array(key,value,array)?的事情

或者在我的情况下,如果我正在寻找“1”的 ID 值,in_array("ID",1,$array)

这是我的解决方案,如果您认为这是正确的方法,请发表评论:

function in_assoc_array($key,$value,$array)
{
    if (empty($array))
        return false;
    else
    {
        foreach($array as $a)
        {
            if ($a[$key] == $value)
                return true;
        }
        return false;
    }
}

【问题讨论】:

  • 我认为您想将键/值对与给定值进行比较。对吗?

标签: php search associative-array


【解决方案1】:

你不能直接在嵌套数组上做。你需要把它嵌套一点,然后再做。

<?php
$arr=array(0=>array('ID'=>1, 'name'=>"Smith"), 1=>array('ID'=>2, 'name'=>"John"));

foreach($arr as $arr1)
{
    if(in_array(1,$arr1))
    {
       echo "Yes found.. and the correspoding key is ".key($arr1)." and the employee is ".$arr1['name'];
    }
}

OUTPUT :

Yes found.. and the correspoding key is ID and the employee is Smith

【讨论】:

  • 猜猜我只需要为它编写自己的函数吧?
  • 不,只是做一个foreach,你可以在里面做。
  • 我编辑了我的帖子,查看代码并告诉我您认为它是否正确,或者是否有办法让它变得更好。
  • @JacobCohen,看到编辑后的答案,你看起来像这样吗?
  • 几乎!我想为我选择的特定键做这件事。不过还是自己写的,谢谢楼主。
【解决方案2】:

试试这个..... 您可以将此函数用于关联数组的任何深度。与此函数不同的是,键值不会在数组中的任何位置重复。

<?php 
function is_in_array($array, $key, $key_value){
      $within_array = 'no';
      foreach( $array as $k=>$v ){
        if( is_array($v) ){
            $within_array = is_in_array($v, $key, $key_value);
            if( $within_array == 'yes' ){
                break;
            }
        } else {
                if( $v == $key_value && $k == $key ){
                        $within_array = 'yes';
                        break;
                }
        }
      }
      return $within_array;
}
$test = array(
                0=> array('ID'=>1, 'name'=>"Smith"), 
                1=> array('ID'=>2, 'name'=>"John")
        );
print_r(is_in_array($test, 'name', 'Smith'));
?>

【讨论】:

  • 我不明白你为什么要写一个新代码,当有一个内置函数时。你可以在下面看到它。另一方面,$k 变量浪费了内存空间,因为它应该只检查值。
  • @AndrewJarvis 虽然已经有一段时间了,你为什么这么说?
  • @JacobCohen 顶层数组上的 foreach 循环和一个简单的 if (isset($array["ID"]) &amp;&amp; $array["ID"] === 1) {} 将用更少的代码完成任务。
【解决方案3】:

首先,您必须知道要在in_array 函数中将关联数组的哪一部分用作干草堆。然后你可以使用in_array 而不需要额外的代码。

值示例:

<?php
$assoc = array(1 => "apple", 2 => "banana", 3 => "lemon", 4 => "pear");
$haystack = array_values($assoc);
echo "<p>" . print_r($assoc, true) . "</p>";

$needle = 'banana';
$find = (in_array($needle, $haystack)) ? 'TRUE' : 'FALSE';
echo "<p>$needle : $find</p>";

$needle = 'cherry';
$find = (in_array($needle, $haystack)) ? 'TRUE' : 'FALSE';
echo "<p>$needle : $find</p>";
?>

结果:

Array ( [1] => apple [2] => banana [3] => lemon [4] => pear )

banana : TRUE

cherry : FALSE

【讨论】:

    【解决方案4】:

    在你的情况下,我想知道简单地使用 isset() 是否更有意义,即

    isset($a[$key])
    

    【讨论】:

    • 当我们知道键和数组是以这种方式设计时使用的。有时我们必须 in_array 进行搜索
    【解决方案5】:

    示例公式,使用类和方法:

    class VerifyInArray
    {
     public function getMyCollection($field, $collection)
     {
         $list = array();
         if (count($collection)) {
            foreach ($collection as $k => $val) {
                $list[] = $val[$field];
            }
         }
         return $list;
     }
    
    public function inMyArray($collection, $field, $findValue)
    {
        if (isset($collection[0])) {
            if (array_key_exists($field, $collection[0]) == false) {
               return 'no'; 
            }
        }
    
        if (in_array($findValue, $this->getMyCollection($field, $collection))) {
            return 'ok';
        }
        return 'no';
    }
    
    public function displayInArray($collection, $attr, $value)
    {
       return 'search result: '. $this->inMyArray($collection, $attr, $value);
    }
    
    }
    $src = new VerifyInArray();
    
     $collection = array(
             array(
                   'ID' => 1, 
                   'name' => 'Smith'
             ), 
             array(
                   'ID' => 2, 
                   'name' => 'John'
             )
        );
    echo $src->displayInArray($collection, 'ID', 2). "\n<br>" .
         $src->displayInArray($collection, 'ID', 0);
    

    Model in ideone

    【讨论】:

      【解决方案6】:

      这是您可以使用的单衬里。

      $isInArray = in_array(1, array_column($names, 'ID'));
      

      $isInArray = 一个布尔值(true 或 false),定义是否在相关数组的请求列中找到给定的值。

      1 = 在数组中搜索的值。

      $names = 有问题的数组。

      'ID' = 数组中我们正在搜索值 1 的列。

      【讨论】:

        【解决方案7】:

        语法

         in_array(mixed $needle, array $haystack, bool $strict = false): bool
        

        Needle 可以是混合类型,所以它可以是任何类型,如果是数字或关联数组都没有问题。

        in_array('foo',array_unique(array_keys($array)));
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-04-07
          • 1970-01-01
          • 1970-01-01
          • 2014-03-20
          • 2014-02-13
          • 2012-01-12
          • 2015-04-30
          相关资源
          最近更新 更多