我正在尝试搜索一个多维数组,当我搜索一个值时,它应该返回它的父键。数组看起来像这样:
[
"fruits" => [
"sweet" => [
"apple",
"banana",
],
"citrus" => [
"lemon",
"orange",
]
],
"vegetables" => [
"leafy" => [
"spinach",
"broccoli",
]
],
]
我希望该函数在搜索
leafy
时返回 broccoli
,或者如果我搜索 leafy
那么它应该返回 vegetables
,但此函数总是返回我 null
:
function recursiveFind(array $haystack, $needle)
{
$foundKey = null;
foreach ($haystack as $key => $value) {
if(is_array($value)) {
if(in_array($needle, $value)){
return $key;
} else {
$foundKey = recursiveFind($value, $needle);
}
}
}
return $foundKey;
}
我尝试的另一个功能如下,它总是返回我
false
:
function recursiveFind(array $haystack, $needle)
{
foreach($haystack as $key => $value) {
$current_key = $key;
if($needle === $value || (is_array($value) && recursiveFind($value, $needle) !== false)) {
return $current_key;
}
}
return false;
}
当只有第二层时,例如,如果我们去除水果和蔬菜包装纸,以上功能就起作用。
请检查此更新的代码,
<?php
$data = [
"fruits" => [
"sweet" => [
"apple",
"banana",
],
"citrus" => [
"lemon",
"orange",
]
],
"vegetables" => [
"leafy" => [
"spinach",
"broccoli",
]
],
];
function recursiveFind(array $datas, $needle) {
foreach ($datas as $key => $data) {
foreach ($data as $inx => $stx) {
if ($needle == $inx) {
return $key;
}
if (in_array($needle, $stx)) {
return $inx;
}
}
}
return null;
}
echo $parentkey = recursiveFind($data, 'broccoli'); // output: leafy
echo $parentkey = recursiveFind($data, 'leafy'); // output: vegetables
?>
function recursiveFind(array $haystack, $needle)
{
foreach($haystack as $key => $data){
foreach($data as $k=>$v){
if($needle==$k){
return $key;
}
if(in_array($needle, $v)){
return $k;
}
}
}
return null;
}
根据您在评论中指定的要求-
public $needle = 'citrus';
private function recursiveFind($haystack, $prev)
{
foreach ($haystack as $key => $data) {
if (is_array($data) && in_array($this->needle, $data)) {
return $key;
}
if ($this->needle === $key) {
return $prev;
}
if (is_array($data)) {
$result = $this->recursiveFind($data, $key);
if ($result != null)
return $result;
}
}
return null;
}
并称其为-
$value = $this->recursiveFind($data, null);
return $value;
请注意,我已将
$needle
声明为类变量。您现在可以将此字段设置为您想要的任何内容。
Happy Coding :)
function recursive_return_array_value_by_key($needle, $haystack){
$return = false;
foreach($haystack as $key => $val){
if(is_array($val)){
$return = recursive_return_array_value_by_key($needle, $val);
}
else if($needle === $key){
return "$val\n";
}
}
return $return;
}