我有以下代码。基本上我想从上到下搜索这个多维数组的键,但忽略具有$ignoreKey
指定的键的子数组。正如您在"array_key_exists"
逻辑中看到的那样,它目前是为一维数组而构建的。我尝试了一些示例但遇到了问题(所以我的1D代码如下所示)。
如果一切按计划进行,我会"thirtyfromgroup1"
回应。
为了实现这一目标,我需要在以下内容中进行哪些更改?
$keyCheck = "30";
$ignoreKey = "group2";
if (array_key_exists($keyCheck, $topLevel)) {
echo $topLevel[$keyCheck];
}
$topLevel = array(
"group1" => array
(
"12" => "twelve",
"30" => "thirtyfromgroup1"
),
"group2" => array
(
"14" => "fourteen",
"30" => "thirty"
),
"group3" => array
(
"12" => "twelve",
"26" => "thirty"
),
);
答案 0 :(得分:3)
假设您只想忽略数组顶层的键,并且只是在第二级搜索键:
$keyCheck = "30";
$ignoreKey = "group2";
$topLevel = array(
"group1" => array(
"12" => "twelve",
"30" => "thirtyfromgroup1"
),
"group2" => array(
"14" => "fourteen",
"30" => "thirty"
),
"group3" => array(
"12" => "twelve",
"26" => "thirty"
),
);
foreach($topLevel as $topKey => $topValue)
{
if ($topKey == $ignoreKey)
continue;
foreach($topValue as $subKey => $subValue)
{
if ($subKey == $keyCheck)
echo $subValue;
}
/* Alternatively:
if (isset($topValue[$keyCheck]))
echo $topValue[$keyCheck];
*/
}