我有一个XML文件,我将其读入PHP数组,以便使用CakePHP的XML :: toArray($ xmlString)函数进行处理。
一切正常,我可以轻松处理数据,但是,当我尝试运行in_array检查时,它会继续返回false,即使我知道值已存在。
这是if语句:
$xmlArray = Xml::toArray($xmlString);
$menus = $xmlArray['navigation'];
$groupId = array($groupId); // Group ID of logged in user, in my case 1
$loggedInId = array($loggedInId); // User ID, in my case 182
//I change them both into arrays, as the second param needs to be an array, and in the XML file, there could only be one value, in which case it's "translated" as a string
//$submenu == foreach($menu['submenu']['menu'] as $subenu)
if(in_array($submenu['permission']['group'],$groupId) || in_array($submenu['permission']['user'],$loggedInId)) {
//do stuff
}
这是XML文件(导航位):
<?xml version="1.0" encoding="utf-8"?>
<navigation>
<menu>
<title>Home</title>
<url>home</url>
<submenus>
<menu>
<title>In memory of...</title>
<url>memoriams</url>
<image>memoriam</image>
<permission>
<group>1</group>
<user>0</user>
</permission>
</menu>
<menu>
<title>Reports</title>
<url>reports</url>
<image>report</image>
<permission>
<group>4</group>
<group>5</group>
<user>252</user>
<user>182</user>
<user>234</user>
</permission>
</menu>
</submenus>
</menu>
</navigation>
菜单仅在第一种情况下显示。也就是说,如果组/用户只有1个值。如果它有多个值,则它不会显示子菜单。
这是对数组的调试:
array(
'menu' => array(
'title' => 'Home',
'url' => 'home',
'submenus' => array(
'menu' => array(
(int) 0 => array(
'title' => 'In memory of...',
'url' => 'memoriams',
'image' => 'memoriam',
'permission' => array(
'group' => '1',
'user' => '0'
)
),
(int) 1 => array(
'title' => 'Reports',
'url' => 'reports',
'image' => 'report',
'permission' => array(
'group' => array(
(int) 0 => '4',
(int) 1 => '5'
),
'user' => array(
(int) 0 => '252',
(int) 1 => '182',
(int) 2 => '234'
)
)
)
)
)
)
)
有没有人知道为什么不想工作?
答案 0 :(得分:2)
函数in_array
的第一个参数是needle
,第二个参数是搜索匹配的array
!!
参考:PHP Manual
答案 1 :(得分:1)
foreach ($menu['menu']['submenus']['menu'] as $submenu) {
$group = $submenu['permission']['group'];
$user = $submenu['permission']['user'];
if(in_array($group, (array) $groupId) || in_array($user, (array) $loggedInId)) {
//do stuff
}
}