简体   繁体   English

in_array似乎不适用于数组

[英]in_array doesn't seem to work on arrays

My php script: 我的PHP脚本:

$cont = array();
$slq_get_previous_country_list = "SELECT country FROM aw_countries_v2 WHERE id ='11120'";
$result_previous_country_list = mysql_query($slq_get_previous_country_list);
while($row = mysql_fetch_assoc($result_previous_country_list))
{
   $cont[] = $row['country'];
}

print_r($cont);                 
$not_data = array();    
$new_contry = array("Greece",
                    "Israel",
                    "Macedonia - The Frm Yugoslav Rep Of",
                    "Malta",
                    "India");


foreach($cont as $c)
{
  if(in_array($c, $new_contry)) 
    {
        echo $c."\n";
    }
    else
    {
        $not_data[] = $c;
    }   
}

print_r($not_data);

$cont array: $cont数组:

Array
(
    [0] =>  Belgium
    [1] =>  Cyprus
    [2] =>  Czech Republic
    [3] =>  Fiji
    [4] =>  Finland
    [5] =>  Greece
    [6] =>  Iceland
    [7] =>  Ireland
    [8] =>  Israel
    [9] =>  Macedonia - The Frm Yugoslav Rep Of
    [10] =>  Malaysia
    [11] =>  Malta
    [12] =>  Monaco
    [13] =>  Poland
    [14] =>  South Africa
    [15] => Austria
)

$not_data array: $not_data数组:

Array
    (
        [0] =>  Belgium
        [1] =>  Cyprus
        [2] =>  Czech Republic
        [3] =>  Fiji
        [4] =>  Finland
        [5] =>  Iceland
        [6] =>  Ireland
        [7] =>  Malaysia
        [8] =>  Monaco
        [9] =>  Poland
        [10] =>  South Africa
        [11] => Austria
    )

The result: 结果:

array(
      [0] => austria
     );

What am I doing wrong? 我究竟做错了什么?

You have spaces in your strings, and the in_array function is space and case sensitive, so try adding this as a precursor: 您的字符串中有空格,并且in_array函数是空格且区分大小写,因此请尝试将其作为前体添加:

while($row = mysql_fetch_assoc($result_previous_country_list))
{
   $cont[] = trim($row['country']);
}

You may also want to try strtolower to compare both array's string values without case worries. 您可能还想尝试strtolower来比较两个数组的字符串值,而无需担心大小写。

Also, it is recommended to NOT use MySQL_ but to develop up to MySQLi or even PDO . 另外,建议不要使用MySQL_,而是要开发MySQLi甚至PDO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM