我有这个数组:
$fruits = array(
[0] => array('name'=>'banana', 'color'=>'yellow' , 'shape'=>'cylinder'),
[1] => array('name'=>'apple', 'color'=>'red' , 'shape'=>'sphere'),
[2] => array('name'=>'orange', 'color'=>'orange' , 'shape'=>'sphere')
)
如何确定数组$fruits
中是否已包含apple
?
我尝试过:in_array("apple", $fruits)
并且没有成功。
我也尝试了各种语法并且与array_key_exists()
混淆了一些,但没有任何结果。有什么想法吗?
答案 0 :(得分:3)
在这种情况下,PHP是出了名的笨拙。最好的全能解决方案是一个简单的foreach
:
$found = false;
foreach ($fruits as $fruit) {
if ($fruit['name'] == 'apple') {
$found = true;
break;
}
}
if ($found) ....
你可以用许多更性感的方式来写这个,但是所有这些都需要额外的内存分配和/或会更慢;如果你不是很有经验,那么很多人也会更难理解。
答案 1 :(得分:1)
foreach($fruits as $fruit)
{
/*In first loop $fruit = array('name'=>'banana', 'color'=>'yellow' ,
'shape'=>'cylinder')
*/
if(in_array("apple",$fruit))
{
/*Using in_array() function we don't have to worry about array keys.
The function checks whether the value exists in given array.
Returns TRUE if value is found in the array, FALSE otherwise.
if(in_array("apple",$fruit)) checks for TRUE
*/
//Do something
}
}
in_array():http://php.net/manual/en/function.in-array.php
foreach():http://php.net/manual/en/control-structures.foreach.php
答案 2 :(得分:1)
$hasApple = false;
foreach ($fruits as $subArray) {
if ($subArray['name'] == "apple")
$hasApple = true;
}
这是正常的解决方案,简单。您也可以尝试使用array_map($fruits, function () use (&$hasApple) { /* ... */ })
。 (但这可能会慢一些......)
从PHP 5.5开始,可能会出现一个问题:
$hasApple = in_array("apple", array_column($fruits, "name"));
答案 3 :(得分:1)
<?php
$fruits = array(
array('name'=>'banana', 'color'=>'yellow' , 'shape'=>'cylinder'),
array('name'=>'apple', 'color'=>'red' , 'shape'=>'sphere'),
array('name'=>'orange', 'color'=>'orange' , 'shape'=>'sphere')
);
$result = false;
foreach($fruits as $subarray) {
if( in_array('apple', $subarray) ) {
$result = true;
break;
}
}
echo "result is ", ($result ? "TRUE" : "FALSE");
?>
答案 4 :(得分:0)
试试这个:
<?PHP
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
$b = array(array('name'=>'banana', 'color'=>'yellow' , 'shape'=>'cylinder'), array('name'=>'apple', 'color'=>'red' , 'shape'=>'sphere'),array('name'=>'orange', 'color'=>'orange' , 'shape'=>'sphere'));
echo in_array_r("apple", $b) ? 'found' : 'not found';
?>
答案 5 :(得分:0)
$hasapple = 0;
foreach($fruits as $keynum)
{
foreach($keynum as $fruitinfokey => $value)
{
if($value == "apple")
{
echo "fruits contains " . $value;
$hasapple = 1;
}
}
}
if($hasapple == 0)
{
echo "The array $fruits does not contain apple";
}
将foreach循环放在另一个foreach循环中以搜索扩展键。
答案 6 :(得分:0)
function arraySearch($value, $array) {
foreach ($array as $key => $val) {
if ($val['name'] === $value) {
return true;
}
}
return null;
}
if(arraySearch('apple',$fruits)){
echo "yes found";
}else{
echo "not found";
}