dpntq48842 2016-10-17 11:54
浏览 16
已采纳

检查多维数组元素是否为数组本身

I'm trying to build a routine which outputs nav menu depending on user status. It needs to be fed a nested array variable (company => role) which looks like:

array(2) {
  ["Company 1"]=>
  array(2) {
    [0]=>
    string(3) "dir"
    [1]=>
    string(5) "manag"
  }
  ["company 2"]=>
  string(3) "dir"
}

It is assumed, that a user can have multiple roles.

Now my routine (simplified version, just to show the logic isnt working):

function get_menu_1  ($status) {

        foreach ($status as $company => $position) {
            $a = is_array($company); //THIS ALWAYS RETURNS FALSE this is for debugging
            echo "<br>this element is array = $a<br>"; //this is for debugging
            if (true == is_array($company)) { // THIS ALWAYS RETURNS FALSE this user in this company has multiple roles

                foreach ($company as $subcompany => $subposition) {
                    echo "<br>$subposition<br>";
                }
            } else { //its not an array, user has one role in the company

                echo "<br>$position<br>";
            }

        }

    }

The output is:

Notice: Array to string conversion in /sata2/home/users/xreact/www/cert.xreact.org/functions.php on line 393

Array

this element is array = 

dir
array(2) { ["Company 1"]=> array(2) { [0]=> string(3) "dir" [1]=> string(5) "manag" } ["Company 2"]=> string(3) "dir" }

For some reason is_array() fails to check whether the variable is array.

  • 写回答

1条回答 默认 最新

  • dtest84004 2016-10-17 11:58
    关注

    you are testing if your array-key is an array itself - but it can't be.

    you have to test the value instead.

    foreach ($status as $company => $position) {
        echo is_array($company); //will allways be false, because the array key is a string.
        //in your examples, "Company 1" or "Company 2";
        if(is_array($position)) {
            echo "here you have your nested array";
        }
    }
    

    edit

    also, on a site node: you could circumvent the check alltogether if you improve your data structure a little bit. instead of storing a single role as string, you can store it as an array with one string element - so your array-value allways is an array:

    $data = array(
        "Company 1"=>array("dir", "manag"),
        "Company 2"=>array("dir")
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器