【问题标题】:in_array not finding the value which is present?in_array 没有找到存在的值?
【发布时间】:2013-09-17 11:42:02
【问题描述】:

这是检查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 时会失败。

【问题讨论】:

  • 抱歉,这个问题可以用“RTFM”轻松回答。因此,就像现在一样,它没有显示出任何研究成果。 -1

标签: php arrays pdo


【解决方案1】:

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
}

【讨论】:

  • 是的,它成功了,感谢您的快速回复。可悲的是,我得到了 3 票反对,但我学到了新东西。
【解决方案2】:

将此函数用于多维数组:

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  ) );

【讨论】:

  • 为什么要给 -1 ?有什么问题?
猜你喜欢
  • 2011-10-21
  • 2014-05-02
  • 2014-05-27
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 2014-02-11
  • 1970-01-01
相关资源
最近更新 更多