查找php中的多维数组中是否存在一个值


Find if a value exits in the multidimensional array in php

是否有办法找到一个值存在于多维数组?

$comments_array = array();
$comments_array[] = array(
               "comment" => "comment1", 
               "flag_user_id" => "1",
                user_id => "2", 
               "username" => "Xylon",
               "comment_id" => "3"
         );
$comments_array[] = array(
               "comment" => "comment2", 
               "flag_user_id" => "4", 
               user_id => "2", 
               "username" => "Xylon", 
               "comment_id" => "6"
             );

在上面给定的数组中,我想查找comment2是否存在并检索它的falg_user_id

这是我为你的问题做的一个例子。

foreach ($comments_array as $arr) {
    if (array_key_exists('comment', $arr) && $arr['comment'] == 'comment2') {
        if (array_key_exists('flag_user_id', $arr)) {
            return $arr['flag_user_id'];
        }
    }
    return NULL;
}

array_key_exists()是一个PHP方法,根据数组中是否存在指定的键返回truefalse。我只是循环遍历多维数组的所有子数组,检查comments索引是否存在,以及它是否等于指定的comment2。如果达到这种情况,它检查flag_user_id索引是否存在并返回它的内容。否则,此循环默认为NULL

希望这对你有帮助!

PHP5.5:

$allComments = array_column($comments_array, 'comment');
$key = array_search('comment2', $allComments);
if($key !== false) {
    $flagUserId = $comments_array[$key]['flag_user_id'];
}

try this

$comment_exists = false;
foreach($comments_array as $arr)
{
    if($arr['comment']=='comment2')
    {
          $comment_exists = true;
    }
}
if($comment_exists)
{
     ehco "exists";
}
else
{
     ehco "not exists";
}
相关文章: