簡體   English   中英

將數組鍵值與給定名稱進行比較

[英]Compare Array key value with the given name

嗨,我正在與循環一些數組操作。

我想將數組鍵值與給定名稱進行比較。

但是我無法獲得確切的輸出。

這是我的數組:

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
        )
)

這是我需要比較的$test_name = "Test2";$test_name = "Test2";

下面我嘗試過的代碼:

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

但是每次它返回NotFound。

沒有得到什么確切的問題。

@Manthan Dave嘗試使用array_column和in_array()如下所示:

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

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

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

我希望您的數組永遠不能包含標簽NotFound ... :)

您可以在下面的數組中嘗試使用數組,

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";
    }

}

只使用in_arrayarray_column而不使用foreach循環作為

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

您只需要檢查以下if條件,因為else第一次滿足時將返回“ 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;

這樣遍歷數組,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM