【发布时间】:2014-07-31 12:08:57
【问题描述】:
给定一个像下面这样的数组,我如何在不使用循环等的情况下检查来自查询字符串的值是否存在于该数组中?
我厌倦了使用 in_array,但即使该值不存在,它似乎也会返回 true。
我需要检查 alias 部分中是否存在该值。
Codepad code of the same thing I posted below.
<?php
$categories = array (
'CAT1' => array('alias' => 'mediterranean-cuisine', 'name' => 'Mediterranean Cuisine'),
'CAT2' => array('alias' => 'asian-cuisine', 'name' => 'Asian Cuisine'),
'CAT3' => array('alias' => 'greek-cuisine', 'name' => 'Green Cuisine')
);
$category = 'asian-cuisine';
if(in_array($category,$categories)) {
echo 'A category with that name was not found! '.$category;
} else {
echo 'A category was found '.$category;
}
echo '<br>';
$category = 'xxx-cuisine';
if(in_array($category,$categories)) {
echo 'A category with that name was not found! '.$category;
} else {
echo 'A category was found '.$category;
}
?>
【问题讨论】:
-
without using loops etc.不管你是否需要循环:为什么这个“要求”? -
您为什么不想使用循环来检查数组中的某些内容?循环是编程中最基本/最基本的控制结构之一......另外,
in_array()在内部使用循环,如果这很重要 -
也许他只是想递归。如果您有没有多个嵌套循环的多维数组,则不能使用简单的
foreach -
@Machavity 如何不能在多维数组上使用
foreach?foreach ($categories as $category => $data) { if ($data['alias'] === $_GET['whatever']) { ... } } -
这听起来像是代码高尔夫,让我们使用
array_filter