Php 在数组中搜索并查找多个键
当我在数组中搜索时,返回第一个键,但我要搜索,如果有相同的值,则返回所有键Php 在数组中搜索并查找多个键,php,arrays,Php,Arrays,当我在数组中搜索时,返回第一个键,但我要搜索,如果有相同的值,则返回所有键 public function array_searchh($needle, $haystack) { foreach ($haystack as $key => $value) { $current_key = ''; $current_key .= $key; if ($needle === $value OR (is_array($value) &
public function array_searchh($needle, $haystack) {
foreach ($haystack as $key => $value) {
$current_key = '';
$current_key .= $key;
if ($needle === $value OR (is_array($value) && $this->array_searchh($needle, $value) !== false)) {
return $current_key;
}
}
return false;
}
在上面的数组中,我有几个“payam”值。当我使用上述函数时,我只返回第一个(找到的)键,但我需要所有匹配的键。不是立即返回键,而是将所有匹配的键收集到一个数组中,并在函数结束时返回此数组
[0] => Array ([id] => 1[value] => payamm)
[1] => Array ([id] =>2[value]=>payam)
[2] => Array ([id] => 25[value] => payam)
[3] => Array ([id] => 3[value] => payam)
[4] => Array ([id] => 4[value] => payam)
[5] => Array ([id] => 5[value] => 340)
也许这个功能会有帮助
public function array_searchh($needle, $haystack) {
$returnKeys = array();
foreach ($haystack as $key => $value) {
$current_key = '';
$current_key .= $key;
if ($needle === $value OR (is_array($value) && $this->array_searchh($needle, $value) !== false)) {
$returnKeys[] = $current_key;
}
}
return (count($returnKeys) > 0) ? $returnKeys : false;
}
这将返回所有找到的键的数组
public function array_searchh($needle, $haystack) {
foreach ($haystack as $key => $value) {
$current_key = '';
$current_key .= $key;
if ($needle === $value OR (is_array($value) && $this->array_searchh($needle, $value) !== false)) {
$foundKeys[] = $current_key;
}
}
if (isset($foundKeys)) {
return $foundKeys;
}
return false;
}