[英]searching inside array values to get primary key in php
I have the following format of an array: 我有以下数组格式:
$array = [
'fruits' => ['apple','orange','banana'],
'vegetables' => ['spinach','broccoli','lettuce']
];
I want to be able to search within the values of fruits and vegetables and get it to return the key (either fruits or vegetables). 我希望能够在水果和蔬菜的值内进行搜索,并使其返回键(水果或蔬菜)。
I have used this: 我用了这个:
$result = array_search('orange', $array);
but $result returns nothing. 但是$ result不返回任何内容。 when it suppose to return 'fruits'.
当它想返回“水果”时。 How do I go about doing that?
我该怎么做?
can use foreach 可以使用foreach
$array = [
'fruits' => ['apple','orange','banana'],
'vegetables' => ['spinach','broccoli','lettuce']
];
foreach ($array as $key => $value) {
if (in_array('orange', $value)) {
echo $key;
}
}
array_search returns the index of the searched value if existed. array_search返回搜索值的索引(如果存在)。 so in my opinion you could do a foreach search and if array_search wasn't empty get the key.
所以我认为您可以进行foreach搜索,如果array_search不为空,则获取密钥。 something like this:
像这样的东西:
foreach ($array as $key => $value){
$result = array_search('orange', $array[$key]);
if($result!==false){
echo "found in ".$key. "at index ".$result;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.