I have an array that’s stored like this:
[0] => Array
(
[id] => 1
[cat_name] => c1
)
[1] => Array
(
[id] => 2
[cat_name] => c2
[copii] => Array
(
[0] => Array
(
[id] => 5
[cat_name] => c21
)
[1] => Array
(
[id] => 6
[cat_name] => c22
)
)
)
[2] => Array
(
[id] => 3
[cat_name] => c3
[copii] => Array
(
[0] => Array
(
[id] => 7
[cat_name] => c31
[copii] => Array
(
[0] => Array
(
[id] => 9
[cat_name] => c311
)
)
)
[1] => Array
(
[id] => 8
[cat_name] => c32
)
)
)
I’m trying to find an easier way of finding a route to a certain ID.
Now I’m using foreach to iterate through all possible arrays and finding the route.
Example:
id = 1:
route[0][id]=1,route[0][cat_name]=c1
id = 5:
route[0][id]=2,route[0][cat_name]=c2
route[1][id]=5,route[1][cat_name]=c21
id = 9:
route[0][id]=3,route[0][cat_name]=c3
route[1][id]=7,route[1][cat_name]=c31
route[2][id]=9,route[2][cat_name]=c311
If my question makes no sense, I blame it on the hours spent trying to find a nice solution to it…
In lieu of posting a bunch of code, I’d suggest you read up on recursion if you don’t know about it. PHP isn’t too great at recursion, but it’s really your only option.
Basically you’d call a function that takes the array, id to find, and a string/array representing the path. Initially call that with a blank string or empty array for the latter parameter.
In the function you would do this:
$array$idyou’re looking for, return the$path.$foundPath = findPath( $array, $id, $path ).$foundPathreturns something, then you’ve got your path and can return.$foundPathis false or null as below), leave it and move on to the next iteration of the loop.Hope that helps!