2017-04-24 70 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']; 
} 
相关问题