in_array没有找到存在的值?

时间:2013-09-17 11:42:02

标签: php arrays pdo

以下是检查contact_id是否存在于特定用户池的池中的代码

function checkid()
{
    $conn = connectPDO();

    $query = "SELECT contact_id FROM contacts WHERE contact_by = :cby";
    $st = $conn->prepare( $query );
    $st->bindValue( ':cby', $this->contact_by, PDO::PARAM_INT );
    $st->execute();
    $row = $st->fetchALL();
    $conn = null;

    print_r($this->contact_id); //1
    print_r($row);     //Array ( [0] => Array ( [contact_id] => 1 [0] => 1 ) [1] => Array ( [contact_id] => 3 [0] => 3 ) ) 

    if( !in_array( $this->contact_id, $row ))
    {
        echo 'You are not authorised to update the details of this contact';
    }
}

这是网址:

http://localhost/contmanager/home.php?action=update&contactid=1

我注意到的一件事是,当我使用fetch而不是fetchall时,它适用于contact_id'1',但在使用fetchALL时失败。

2 个答案:

答案 0 :(得分:2)

in_array不适用于多维数组,解决方法是:

foreach( $row as $each ){  #collect all the ids in an array
    $temp[] = $each['contact_id'];
}

然后检查in_array

if( !in_array( $this->contact_id, $temp )){
    //your code here
}

答案 1 :(得分:-1)

将此函数用于多维数组:

function in_multiarray($elem, $array)
{
    $top = sizeof($array) - 1;
    $bottom = 0;
    while($bottom <= $top)
    {
        if($array[$bottom] == $elem)
            return true;
        else 
            if(is_array($array[$bottom]))
                if(in_multiarray($elem, ($array[$bottom])))
                    return true;

        $bottom++;
    }        
    return false;
}

示例:

$array = array( array( 'contact_id' => '1' , 1 ) , array( 'contact_id' => '3' , 3 ) );
var_dump( in_multiarray( 1 , $array  ) );