[英]find if key is in a multidimentional array
i am creating a multidimentional array and i wish to know why the following code is not working and why the other with same value when im fetching the same array is actually working. 我正在创建一个多维数组,我想知道为什么以下代码无法正常工作,以及为什么在提取相同数组时另一个具有相同值的代码实际上是有效的。
$fruits = array(
"sale"=> array("banana", "apple", "orange"),
"regular"=> array("grapes", "pear", "ananas")
);
then in the first case it return false 然后在第一种情况下,它返回false
1st case : 第一种情况:
$find_price = 'sale';
if(in_array($find_price, $fruits)){
return true;
}
else {
return false;
}
and in second example i got a result of true 在第二个示例中,我得到的结果为true
$find_price = 'sale';
if(isset($fruit[$find_price])){
return true;
}
else {
return false;
}
in_array()
used to determine the value is in array or not. in_array()
用于确定值是否在数组中。 If you want to find if the key exist so array_key_exists
is your friend 如果您想查找密钥是否存在,那么array_key_exists
是您的朋友
Look at the below snippet. 请看下面的代码片段。
$find_price = 'sale';
if(array_key_exists($find_price, $fruits)){
return true;
}
else {
return false;
}
In your first code 在您的第一个代码中
$find_price = 'sale';
if(in_array($find_price, $fruits)){
return true;
}
else {
return false;
}
You use in_array()
. 您使用in_array()
。 This in_array()
function the elements into the array, That element exist in array or not. 这个in_array()
函数将元素放入数组中,该元素是否存在于数组中。 And you are finding a value which is key in the array. 并且您正在找到一个值,该值是数组中的键。 Instead of in_array()
you can use array_key_exists()
. 可以使用array_key_exists()
代替in_array()
array_key_exists()
。
Your second code 您的第二个代码
$find_price = 'sale';
if(isset($fruit[$find_price])){
return true;
}
else {
return false;
}
You are using isset()
this function tell that the element you find, is exist in code or not. 您正在使用isset()
这个函数告诉您找到的元素是否存在于代码中。 Like you are finding isset($fruit[$find_price])
means isset($fruit['sale'])
that is exist.... 就像您正在发现isset($fruit[$find_price])
意味着存在的isset($fruit['sale'])
。...
Thats why this condition is true.. 这就是为什么这个条件成立的原因。
You have to use loop for this type of conditions. 您必须对这种类型的条件使用循环。 try this. 尝试这个。
foreach($fruits as $key => $value)
{
if($fruits[$key]['sale'])
{
return true;
}
else
{
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.