2017-04-21 47 views
1

嗨,我正在使用循環的一些數組操作。將數組鍵值與給定名稱比較

我想比較陣列鍵值與給定的名稱。

但我無法得到確切的輸出。

這是我的數組:

Array 
(
    [0] => Array 
     (
      [label] => 
      [value] => 
     ) 

    [1] => Array 
     (
      [label] => 3M 
      [value] => 76 
     ) 

    [2] => Array 
     (
      [label] => Test 
      [value] => 4 
     ) 

    [3] => Array 
     (
      [label] => Test1 
      [value] => 5 
     ) 

    [4] => Array 
     (
      [label] => Test2 
      [value] => 6 
     ) 
) 

這是我varriable,我需要比較:$test_name = "Test2";

下面的代碼,我曾嘗試:

$details // getting array in this varriable 
if($details['label'] == $test_name) 
{ 
    return $test_name; 
} 
else 
{ 
    return "NotFound"; 
} 

但每次重新變成NotFound。

沒有得到什麼問題。

+0

給你的循環代碼,這樣可以遍歷並給予特定的答案。 – Hacker

+0

@Manthan Dave更新了答案 – Sathish

回答

4

@Manthan戴夫與array_column和in_array(試行)象下面這樣:

<?php 
if(in_array($test_name, array_column($details, "label"))){ 
    return $test_name; 
} 
else 
{ 
    return "NotFound"; 
} 
3

$details是一個多維數組,但您試圖像訪問一個簡單的數組。
您需要太多遍歷它:

foreach ($details as $item) { 
    if($item['label'] == $test_name) 
    { 
     return $test_name; 
    } 
    else 
    { 
     return "NotFound"; 
    } 
} 

我希望你的陣列不能包含一個標籤NotFound ... :)

+0

已經嘗試返回相同。沒有找到 –

2

你有內部陣列陣列嘗試下面,

if($details[4]['label'] == $test_name) 
{ 
    return $test_name; 
} 
else 
{ 
    return "NotFound"; 
} 

雖然foreach循環應該工作,但如果不嘗試的,

for($i=0; $i<count($details); $i++){ 

    if($details[$i]['label'] == $test_name) 
    { 
     return $test_name; 
    } 
    else 
    { 
     return "NotFound"; 
    } 

} 
2

只需使用in_arrayarray_column不使用foreach環路作爲

if (in_array($test_name,array_column($details, 'label'))) 
{ 
    return $test_name; 
} 
else 
{ 
    return "NotFound"; 
} 
+0

相同的邏輯:D現在該怎麼辦? –

+0

想做動態 –

+0

@Saty但你的回答是不正確的,它不會輸出任何內容 –

2

你只需要檢查if條件如下所示,因爲在第一次會見時它會返回「notfound」,那麼它將不會執行。

$result = 'NotFound'; 
foreach ($details as $item) { 
    if($item['label'] == $test_name) 
    { 
     $result = $test_name; 
    } 
} 
return $result; 

$result = 'NotFound'; 
if (in_array($test_name,array_column($details, 'label'))) 
{ 
    $result = $test_name; 
} 
return $result; 
+0

你的回答是不正確的,它會爲第一種情況輸出什麼 –

+0

爲什麼?你可以解釋嗎? – Sathish

+1

現在好了,您已將列名'firstname'編輯爲'label' –

2

遍歷您的陣列這樣,

array_walk($array, function($v) use($test_name){echo $v['label'] == $test_name ? $test_name : "NotFound";}); 
+1

豎起陣列 – Sathish