2012-01-04 20 views
3

我的英語發佈對此非常抱歉。使用in_array在多維數組中搜索

我有一個數組:

Array ([name] => Array 
         ( 
         [0] => Sorry the name is missing! 
         [1] => Sorry the name is to short! 
        ) 
) 

現在我想用in_array爲如 「名」,以測試。

if (in_array("name", $false["name"])) { 
echo "the array keys"; 
} 

但它dsnt的工作。請annybody幫助我嗎?非常感謝。

+0

當您測試* name *時,測試的結果應該是什麼?那個* name *是一個數組還是一個字符串? – hakre 2012-01-04 14:06:08

回答

10

嘗試array_key_exists():link

if(array_key_exists('name', $false['name'])) { 
    echo $false['name'][0]; // or [1] .. or whatever you want to echo 
} 
0

in_array()查找精確值。所以你需要指定"Sorry the name is missing!"而不是"name"

例如:

if (in_array("Sorry the name is missing!", $false["name"])) { 
    echo "the array keys"; 
} 

其中:

$false = array('name' => array( 
    0 => 'Sorry the name is missing!', 
    1 => 'Sorry the name is to short!'), 
); 
0

If you are searching for array key name in your main array:

$arr = array("name" => array( 
         "0" => "Sorry the name is missing!", 
         "1" => "Sorry the name is to short!" 
       )); 

if(array_key_exists('name', $arr)) { 
    print_r($arr['name']); 
} else { 
    echo "array key not found"; 
} 

Demo

它不會找到,如果你將在$改編[「名」]搜索,因爲它僅包含和在這個級別數組鍵。

1

也許你需要通過數組先走,然後檢查其

function in_multiarray($str, $array) 
{ 
    $exists = false; 

    if (is_array($array)) { 
     foreach ($array as $arr): 
      $exists = in_multiarray($str, $arr); 
     endforeach; 
    } else { 
     echo $array . ' = ' . $str . "\n"; 
     if (strpos($array, $str) !== false) $exists = true; 
    } 

    return $exists; 
} 
3

in_array()不多維數組工作,所以它是不可能在這裏使用in_array()。當您在in_array()中搜索「名稱」時,它會在第一個數組中搜索並查找名爲「name」的數組的鍵。

更好使用array_key_exists功能。一個例子如下:(記住它僅僅是一個建議代碼可能會有所不同)

if(array_key_exists('name', $false['name'])) { 
    echo $false['name'][0]; // or [1] .. or whatever you want to echo 
} 
//$false['name'] array contains your searched data in different keys; 0,1,2,.... 

您可以使用foreach()循環第一陣列,然後使用in_array()搜索,但不會是一個很好的方法,因爲它會採取有更多的時間去尋找。
祝您好運:)的

0

如果你想使用in_array 你只需要把作爲數組定義了第二個參數 例如

if(in_array('name',$false){ 
//do your stuff 
print_r($false['name']); //this will print the array of name inclusive of [0] and [1] 
} 

有在in_array php manual賦予了更多的例子。請檢查一下。