douliang2167 2013-10-16 18:47
浏览 33
已采纳

从函数结果 - PHP中检查数组中是否存在键

I have a function which checks the children on a tree given the parent ID:

function categoryChild($id) {

    $mysqli = dbConnect();

    $query = "select folders_id, childof from folders where childof = $id";
    $result = $mysqli->query($query);

    $children = array();

    if(mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_array($result)) {
            $children[$row['folders_id']] = categoryChild($row['folders_id']);
        }
    }

    return $children;
}

If I use: print_r(categoryChild($folder_id)); I get e.g. the following:

Array ( [21] => Array ( [22] => Array ( ) ) [24] => Array ( [25] => Array ( ) ) ) 

I want to be able to check simply check against the numbers in the array(s)...I've tried:

if(in_array ("25", categoryChild($folder_id))){
    echo 'yeah';
};

But it simply does nothing.

Is there a way to do this?

  • 写回答

2条回答 默认 最新

  • douqing0713 2013-10-16 19:02
    关注

    What you want is to check the key no the value

    in_array you are checking if the value exist

    You have to use array_key_exists in order to check the key

    if (array_key_exists(25, categoryChild($folder_id))) {
        echo 'yeah';
     }
    

    To find a key in nested array you can use this:

     $keySearch=25;
     $array=categoryChild($folder_id);
    
    foreach ($array as $array_data) {
        if (array_key_exists($keySearch, $array_data)) {
         echo 'yeah';
        }
    }
    

    NOTE:

    25 is INT no a string

    A useful link how to prevent SQL Injections in PHP

    UPDATE

    if your array is something like this

    $array = array(
        21 => '',
        24 => array(
            22 => '',
            25 => ''
        )
    );
    
    $keySearch = 21;
    
    if (count($array) == count($array, COUNT_RECURSIVE)) {
    //  single array
      if (array_key_exists($keySearch, $array)) {
        $result = 'yeah1';
      }else{
        $result = 'no';
      }
    } else {
    //  nested array;
      foreach ($array as $value) {
        if (array_key_exists($keySearch, $array)) {
          $result = 'yeah2';
        }else{
          $result='no';
        }
      }
    }
    
    echo $result;//output yeah2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题