2017-04-21 45 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