如何检查多维数组中的数组键?

时间:2017-01-13 04:35:33

标签: php arrays multidimensional-array

如何检查数组中是否存在数组键?

我需要检查数组中是否存在用户ID,我找到了下面的数组,

 Array
(

  [0] => Array
    (
        [user_id] => 1482309797
        [week] => 1
        [type] => 1
        [commission] => 4000
    )

[1] => Array
    (
        [user_id] => 1482309797
        [week] => 1
        [type] => 1
        [commission] => 0
    )

[2] => Array
    (
        [user_id] => 1482309797
        [week] => 1
        [type] => 1
        [commission] => 4000
    )

[3] => Array
    (
        [user_id] => 1482309797
        [week] => 1
        [type] => 1
        [commission] => 0
    )

[4] => Array
    (
        [user_id] => 1483096072
        [week] => 1
        [type] => 1
        [commission] => 4000
    )

[5] => Array
    (
        [user_id] => 1483333245
        [week] => 1
        [type] => 1
        [commission] => 2000
    )

我想检查用户ID是否存在,我试过下面的代码

        foreach ($com_array as $report) {

         $user_id=$report['user_id'];

        if(array_key_exists($user_id,$output_array)){
                echo "Eid found";
         }else{
                echo "id not found";
            }

        }

任何人请帮助。

4 个答案:

答案 0 :(得分:1)

试试这个......

foreach ($com_array as $key=>$value) {
        if(array_key_exists("user_id",$value)){
                echo "id found";
         }else{
                echo "id not found";
            }

        }

答案 1 :(得分:1)

  foreach ($com_array as $report) {
     if(isset($report['user_id'])){
         echo "Eid found";
     }else{
         echo "id not found";
     }
  }

尝试上面的代码,您将获得输出。

答案 2 :(得分:0)

多维数组没有内置函数。你可以做一个像:

function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key == $keySearch) {
            echo 'yes, it exists';
            return true;
        }
        else {
            if (is_array($item) && findKey($item, $keySearch)) {
               return true;
            }
        }
    }

    return false;
}

答案 3 :(得分:0)

如果您只是检查是否存在密钥,则可以执行此操作。

$user_id_arr = array_column($output_array, 'user_id'); // Get your user_id to a single dimension array
foreach ($com_array as $report) {
    if ( in_array($report['user_id'], $user_id_arr) ){
        echo "ID Found";
    } else {
        echo "ID Not Found";
    }
}

谢谢!