繁体   English   中英

如何使用php检查字符串是否在数组中?

[英]How to check if string is in array with php?

当 var_dump 时,我有一个如下所示的数组:

 array(3) { [0]=> array(3) { ["id"]=> string(1) "3" ["category"]=> string(5) "staff" ["num_posts"]=> string(1) "1" } [1]=> array(3) { ["id"]=> string(1) "1" ["category"]=> string(7) "general" ["num_posts"]=> string(1) "4" } [2]=> array(3) { ["id"]=> string(1) "2" ["category"]=> string(6) "events" ["num_posts"]=> string(1) "1" } }

如果数组不包含以下字符串,我需要回显一个值:'hello'

这怎么可能,我曾尝试使用 in_array,但没有成功。 帮助表示赞赏。

foreach ($array as $subarray)
{
   if(!in_array('hello', $subarray))
   {
      echo 'echo the value';
   }
}

对于多维数组,请尝试:


function in_array_r($needle, $haystack, $strict = true) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

$attendance = ['present','absent','present','present','present','present'];

if (in_array("absent", $attendance)){

     echo "student is failed";

  } else {
     
      echo "student is passed";    
   }

尝试这个

$array = array( array("id" => "3","category" => "hello" ,"num_posts" =>  "1" ),
    array( "id"=> "1","category"=> "general" ,"num_posts" => "4" ),
    array( "id"=> "2" ,"category"=> "events","num_posts"=>  "1" ));

foreach($array as $value){
    if(!in_array("hello", $value)){
        var_dump($value);
    }
}

它的工作

如果你想在每个维度上搜索,试试这个:

function value_exists($array, $search) {
    foreach($array as $value) {
        if(is_array($value)) {
            if(true === value_exists($value, $search)) {
                return true;
            }
        }
        else if($value == $search) {
            return true;
        }
    }

    return false;
}

if(value_exists($my_array, 'hello')) {
    echo 'ok';
}
else {
    echo 'not found';
}
$isExistHelloInArray = array_filter($array,function($element) {
    return $element['category'] == 'hello';
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM