Reputation: 1106
I am trying to search a multidimensional array, where when I search for a value it should return me its parent key. Array looks like this:
[
"fruits" => [
"sweet" => [
"apple",
"banana",
],
"citrus" => [
"lemon",
"orange",
]
],
"vegetables" => [
"leafy" => [
"spinach",
"broccoli",
]
],
]
I want the function to return leafy
when I search for broccoli
or if I search for leafy
then it should return vegetables
but this function always return me 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;
}
One more function I tried is as below, which returns me false
always:
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;
}
Above function works when there is only second level for example if we remove fruits and vegetable wrappers.
Upvotes: 1
Views: 636
Reputation: 9853
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;
}
As per your requirement specified in comments-
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;
}
And call this like-
$value = $this->recursiveFind($data, null);
return $value;
Notice that I have declared $needle
as a class variable. You can set this field anything you want now.
Happy Coding :)
Upvotes: 1
Reputation: 937
Please check this updated code,
<?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
?>
Upvotes: 3
Reputation: 91
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;
}
Upvotes: 0