Ho questo array pagliaio:ricerca ricorsiva in array PHP con il percorso
$array = [
[
"name" => "Intro",
"id" => "123",
"children" => [
"name" => "foo",
"id" => "234",
"children" => [
"name" => "mur",
"id" => "445",
]
]
],[
"name" => "chapter one",
"id" => "9876",
"children" => [
"name" => "foo",
"id" => "712",
"children" => [
"name" => "bar",
"id" => "888",
]
]
]
];
E questo array ago: $needle = ["chapter one","foo","bar"]
Sto lavorando a una funzione di ricerca ricorsiva che restituirà il valore della id
corrispondenza elemento figlio sulla colonna name
seguendo il percorso di $needle
.
Nell'esempio, deve restituire 888
. Ho fatto questo finora ma non trovo il modo di seguire il percorso $ ago invece di trovare valori supponendo che siano unici. Apprezzo qualsiasi aiuto che mi metta sulla buona strada.
function searchTree($needle, $haystack, $strict=false, $path=array())
{
if(!is_array($haystack)) {
return false;
}
foreach($haystack as $key => $val) {
if(is_array($val) && $subPath = searchTree($needle, $val, $strict, $path)) {
$path = array_merge($path, array($key), $subPath);
return $path;
} elseif((!$strict && $val == $needle) || ($strict && $val === $needle)) {
$path[] = $key;
return $path;
}
}
return false;
}
presumo dal momento che è ricorsivo, che '$ needle' può contenere valori infiniti o sarà sempre 3? – Darren
@Darren davvero valori infiniti. E gli oggetti allo stesso livello di un array hanno nomi univoci. – greener