我正在尝试构建一个根据用户状态输出导航菜单的例程。它需要提供一个嵌套的数组变量(company => role),它看起来像:
array(2) {
["Company 1"]=>
array(2) {
[0]=>
string(3) "dir"
[1]=>
string(5) "manag"
}
["company 2"]=>
string(3) "dir"
}
假设用户可以拥有多个角色。
现在我的例程(简化版,只是为了显示逻辑不起作用):
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>";
}
}
}
输出结果为:
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" }
由于某种原因,is_array()
无法检查变量是否为数组。
答案 0 :(得分:5)
您正在测试您的array- 键是否是一个数组本身 - 但它不能。
你必须测试这个值。
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";
}
}
修改强>
另外,在站点节点上:如果您稍微改进数据结构,则可以完全避免检查。 而不是将单个角色存储为字符串,您可以将其存储为具有一个字符串元素的数组 - 因此您的数组值始终是一个数组:
$data = array(
"Company 1"=>array("dir", "manag"),
"Company 2"=>array("dir")
);