2011-02-12 105 views
0

在我的剧本,PHP数组变量

$value= array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"); 

if(in_array("Bloomsberry",$value)){ 
echo "Bloomsberry is there inside the array";} 
else{ echo "Bloomsberry is not there ";} 

这个效果很好

我有一个变量$names这是一个MySQL的结果,其中有数据"DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"像数组数据。

但是当我变量存放内部像$value= array($names);代替$value= array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");,我得到预期"Bloomsberry is there inside the array"

回答

1

我怀疑“的招牌便得到了转义,并且也将数组作为单个传递字符串,你必须将字符串拆分为一个数组,如果我将你提交给mysql的地方:“DK,Bloomsberry,McGrawHill”等等,然后做

<?php 
$string = "DK,Bloomsberry,McGrawHill,OXFORD,DC Books,Springer"; 
$array = explode(",", $string); 
if(in_array("Bloomsberry",$array)){ 
    echo "Bloomsberry is there inside the array";} 
else{ echo "Bloomsberry is not there ";} 

explode命令返回逗号上的数组拆分。 我希望这对你的作品

1

的结果"Bloomsberry is not there "代替如果$names已经是一个阵列,然后array($names)是含有一种元素的阵列(一个元件是你的$names阵列)。

如果你想分配给$value数组$names,您只需使用赋值运算符:

$value = $names; 

然后做你的条件in_array("Bloomsberry", $value);。或者你可以避免这项任务,并做in_array("Bloomsberry", $names)

0

问题:

这是因为in_array开始在根节点检查,并根据多少级针具有取决于它的草垛

的一个例子中多少级检查以上:

$a = array(array('p', 'h'), array('p', 'r'), 'o'); 

if (in_array(array('p', 'h'), $a)) 
{ 
    echo "'ph' was found\n"; 
} 

$a实际上是2级的数组,也叫多维。

在您的代码中,将您的根级阵列放入另一个阵列中,从而将数组的数组变为array(array("results")),当您使用in_array("string")检查第一个节点时,它无法在根haystack中找到它。

可能的修正:

只需要用实际结果作为in_array检查,例如:

while($row = mysql_fetch_array($result)) 
{ 
    /* 
     $row is a single dimension and can be used like so: 
    */ 
    if(in_array("Bloomsberry"),$row)) 
    { 
     //Echo your success. 
    } 
} 
1

注意以下区别:

$value = array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"); 
print_r($value); 

/* produces: 
Array 
(
    [0] => DK 
    [1] => Bloomsberry 
    [2] => McGrawHill 
    [3] => OXFORD 
    [4] => DC Books 
    [5] => Springer 
) 
*/ 

,其中为:

$value = array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"); 
$newValue = array($value); 
print_r($newValue); 

/* produces: 
Array 
(
    [0] => Array 
    (
     [0] => DK 
     [1] => Bloomsberry 
     [2] => McGrawHill 
     [3] => OXFORD 
     [4] => DC Books 
     [5] => Springer 
    ) 
) 
*/ 

in_array("Bloomsberry", $newValue)如果“Bloomsberry”是第一维的值将只返回true阵列。但是,$ newValue中唯一的第一个维度元素是$ value数组。

0

试试这个

$name = '"DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"'; 
$name = str_replace('"', '', $name); 
$value = explode(',', $name); 

现在你下面给出的代码将工作。

if(in_array("Bloomsberry",$value)){ 
echo "Bloomsberry is there inside the array";} 
else{ echo "Bloomsberry is not there ";}