开发者

Search array path with related values

I'm working on a menu system and am working on some complex issues. The menu is generated from a array. This array is included in a pastebin because it's really big. I want to search in the array and get the hierarchical path of the value I'm searching while also getting the values next to the parents you run trough. As I s开发者_如何学Goaid its quite complex.

In the pastebin is the array and the result I want to function to return:

-->pastebin<--

I tried writing this function quite a few times but always get stuck in the middle.


Here is a function:

function get_item_recursive($id, $menu_array = array())
{
    foreach($menu_array as $menu_item)
    {
         if(isset($menu_item['id']) && $menu_item['id'] == $id)
         {
             $menu_item['subitems'] = array();
             return $menu_item;
         }
         else
         {
             if(isset($menu_item['subitems']) && !empty($menu_item['subitems']))
             {
                 $found = get_item_recursive($id, $menu_item['subitems']);
                 if($found)
                 {
                     return $menu_item;
                 }
             }
         }
    }
    return FALSE;
}

I have not tested it, but this is the idea.


You are basically looking for the path to build something like a breadcrumb? You can use a recursive function for that:

function findPath($haystack, $id, $parents = array()) {
   foreach ($haystack as $k => $v) {
      if ($v['id'] == $id) {
         return array_merge($parents, array($v));
      } else if (!empty($v['subitems'])) {
         unset($v['subitems']);
         $return = findPath(
            $haystack[$k]['subitems'],
            $id,
            array_merge($parents, array($v))
         );
         if ($return) return $return;
      }
   }
   return false;
}

Executing this function like this:

findPath($haystack, 11);

Would return:

Array (
   [in-balans] => Array
      (
         [id] => 2
         [slug] => in-balans
         [title] => In balans
      )
   [arbodienstverlening] => Array
      (
         [id] => 10
         [slug] => arbodienstverlening
         [title] => Arbodienstverlening
      )
   [arbo] => Array
      (
         [id] => 11
         [slug] => arbo
         [title] => Arbo
         [subitems] =>
      )
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜