How to use PHP in_array with associative array?

前端 未结 6 1695
夕颜
夕颜 2020-12-03 00:15

Is there any php function such as in_array for associative arrays you get by the mysql function \"mysql_fetch assoc\" ?

For example, if I have an $array that looks l

6条回答
  •  醉话见心
    2020-12-03 00:33

    The sample formule, using class and methods:

    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
    " . $src->displayInArray($collection, 'ID', 0);

    Model in ideone

提交回复
热议问题