检查值是否存在于多维数组中 [英] check if value exists in multidimensional array
问题描述
我想使我的类别菜单响应所显示的项目.这些项目具有多个类别,因此可以激活多个类别菜单链接.项目所属的类别是在多维数组中包含的php文件中指定的.
I want to make my category menu responsive to the projects displayed. The projects have multiple categories so multiple category-menu-links can be active. Whichever category the project belongs to is specified on an included php file in an multidimensional array…
例如
$allProjects = array(
'project1' => array('corporate'),
'project2' => array('corporate', 'print'),
'project3' => array('web')
);
现在,我想检查每个类别是否是数组$ allProjects中数组'project1','project2','project3'...的值,如果是,则回显'active'.
Now I want to check for each category if it is a value of the array 'project1', 'project2', 'project3',… within the array $allProjects and if so echo 'active'.
到目前为止,我有...
So far I have…
<?php if (($_GET['cat'] == 'corporate')) {echo 'active';}; || if (isset ($_GET['project'])) {if in_array('corporate', $_GET['project']) {echo 'active';}; ?>
这有意义吗?
更新:
我需要在特定键(第二级数组)处检查多维数组是否存在值(第三级数组)
What I need is to check in the multidimensional array at a specific key (2nd level array) if a value exists (3rd level array)
所以我猜是这样的……
$project = $_GET('project');
$category = $_GET('cat');
foreach ($allProjects as $project => $categories) {
if in_array($category, $project);
echo 'yes';
}
我使用$ project(上面定义的变量)作为键,但这不起作用.它期望参数为数组.我只想使用项目名称(在$ project中定义)作为in_array函数的键,并检查值中$ category的出现.
I use $project, variables defined above, as key but that doesn't work. It expects the parameters to be arrays. All I want is to use the name of the project (defined in $project) as a key for the in_array function and check for appearance of $category in the values.
感谢帮助
推荐答案
您可以使用 array_search()
在数组中搜索特定值.如果找到该函数,则返回与该值对应的键,否则返回 false
.
You can use array_search()
to search for a specific value in your array. This function returns the key corresponding to the value if found, false
otherwise.
所以您要做的是循环每个子数组:
So what you will want to do is loop each subarray:
$category = $_GET['cat'];
$allProjects = array(
'project1' => array('corporate'),
'project2' => array('corporate', 'print'),
'project3' => array('web')
);
foreach ($allProjects as $projectName => $categories) {
$categoryIndex = array_search($category, $categories);
if ($categoryIndex !== false) {
echo 'active: ' . $categoryIndex;
// Do something with $categoryIndex and $projectName here
}
}
更新:
看起来这是您的答案:
$project = $_GET('project');
$category = $_GET('cat');
if (isset($allProjects[$project]) && in_array($category, $allProjects[$project])) {
echo 'yes';
}
这篇关于检查值是否存在于多维数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!