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.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试构建一个根据用户状态输出导航菜单的例程。 它需要提供一个嵌套的数组变量(company =&gt; role),它看起来像:

  array(2){
 [“Company 1”] =&gt;  
 array(2){
 [0] =&gt; 
 string(3)“dir”
 [1] =&gt; 
 string(5)“manag”
} 
 [“公司2  “] =&gt; 
 string(3)”dir“
} 
   
 
 

假设用户可以拥有多个角色。

现在我的例程(简化版,只是为了显示逻辑不起作用):

  function get_menu_1($ status){
 
 foreach(  $ status as $ company =&gt; $ position){
 $ a = is_array($ company);  //总是返回FALSE这是调试
 echo“&lt; br&gt;这个元素是array = $ a&lt; br&gt;”;  //这是用于调试
 if(true == is_array($ company)){//总是返回FALSE这个公司的用户有多个角色
 
 foreach($ company as $ subcompany =&gt; $ subposition  ){
 echo“&lt; br&gt; $ subposition&lt; br&gt;”; 
} 
} else {//它不是数组,用户在公司中有一个角色
 
 echo“&lt; br&gt; $ 位置&lt; br&gt;“; 
} 
 
} 
 
} 
   
 
 

输出为:

 注意:第393行/sata2/home/users/xreact/www/cert.xreact.org/functions.php中的数组到字符串转换
 
Array 
 
这个元素是array = 
 
dir  
array(2){[“Company 1”] =&gt;  array(2){[0] =&gt;  string(3)“dir”[1] =&gt;  string(5)“manag”} [“公司2”] =&gt;  string(3)“dir”} 
   
 
 

由于某种原因, is_array()无法检查变量是否为数组。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题