2017-04-24 73 views
-1

您好我正在做一些操作,我需要從它的鍵中獲取數組的值。如何獲得基於鍵匹配的數組值

我有$attr_color變量值爲red

因此,如果red在數組中,那麼它需要返回它的值。

下面是我的數組:

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

    [1] => Array 
     (
      [label] => red 
      [value] => 32 
     ) 

    [2] => Array 
     (
      [label] => green 
      [value] => 33 
     ) 

    [3] => Array 
     (
      [label] => pink 
      [value] => 34 
     ) 

    [4] => Array 
     (
      [label] => black 
      [value] => 35 
     ) 

    [5] => Array 
     (
      [label] => white 
      [value] => 36 
     ) 

) 

我曾嘗試下面的代碼,但它返回空白:

$attr_color = "red"; 

//$response is my array which i have mention above. 
if(in_array($attr_color,array_column($response,"label"))) 
{ 

    $value = $response['value']; 
    echo "Value".$value; 
    exit; 
} 

幫助?我犯了什麼錯誤?

+0

你無法直接訪問$ response ['value']。這就是你在做錯什麼 –

+0

你必須用'label = red'獲得數組的索引,然後使用'$ response [$ index] ['value']' –

回答

2

使用array_search並檢查錯誤

$index = array_search($attr_color, array_column($response,"label")); 
if ($index !== false) { 
    echo $response[$index]['value']; 
} 
+0

同樣的答案給我和downvote那 –

+0

實際執行這個,這對我來說實際上是可行的解決方案謝謝 –

0

使用array_search而不是in_array

$attr_color = "red"; 

if(($index = array_search($attr_color,array_column($response,"label")))!==FALSE) 
{ 

    $value = $response[$index]['value']; 
    echo "Value".$value; 
    exit; 
} 
+0

當它出現在數組的第一個元素 – trincot

+0

'array_search'返回匹配的索引,如果數組中沒有相應的顏色,則返回false。我在這裏搜索標籤數組,而不是原始數組。這是最短的解決方案,而不是使用foreach循環。但我尊重你所有的答案。 –

+0

您是否嘗試了我在第一條評論中指出的內容?你有輸出嗎? – trincot

0

嘗試:

$attr_color = "red"; 

//$response is my array which i have mention above. 

$index = array_search($attr_color, array_column($response, 'label')); 

if($index!==false){ 
    $value = $response[$index]['value']; 
    echo "Value:".$value; 
    exit; 
} 

這裏$指數將得到數組的索引標籤爲紅色

+0

已更新,請檢查這個代碼 –

+0

爲什麼'downvote'? –

+0

當它發生在數組的第一個元素時,它不會找到顏色 – trincot

2

試試這個簡單的解決方案,希望這將幫助你。這裏我們使用array_column用於獲取專欄,並與keysvalues,凡keyslabelsvalues索引它作爲value

Try this code snippet(樣本輸入)

$result=array_column($array, 'value',"label"); 
$result=array_filter($result); 
echo $result["red"]; 
2

你的情況,這足以使用常規foreach循環:

$attr_color = "red"; 
$value = ""; 

foreach ($response as $item) { 
    if ($item['label'] == $attr_color) { 
     $value = $item['value']; 
     break; // avoids redundant iterations 
    } 
} 
1

使用array_column與第三個參數和array_search作爲

$attr_color="red"; 
$arr = array_filter(array_column($response, "label", 'value'));// pass thired parameter to make its key 
    if (array_search($attr_color, $arr)) {// use array search here 

     echo array_search($attr_color, $arr); 
    } 
+0

@薩蒂在做選票嗎? –

+0

@trincot plz檢查https://3v4l.org/WX5ZZ – Saty

+1

的確,這個解決方案的工作原理。 – trincot

1

試試下面的代碼:使用數組匹配功能:

$your_value = array_search($attr_color, array_column($response,"label")); 
if ($index !== false) { 
    echo $response[$your_value]['value']; 
} 
相關問題