search for a value in a multi dimensional array and get its path in PHP

前端 未结 1 738
逝去的感伤
逝去的感伤 2021-01-27 06:24

This is my array:

$array = array (
\'1\' => array(
  \'title\' => \'Level1\',
  \'nodes\' => array(
   \'11\' => array(\'title\' => \'sub1_company         


        
相关标签:
1条回答
  • 2021-01-27 06:58

    You need a recursive function, not an iterative one.

    function breadcrumb($tree, $needle, &$result = array()) {
    
        $result = array();
    
        if (is_array($tree)) {
            foreach ($tree as $node) {
                if ($node['title'] == $needle) {
                    $result[] = $node['title'];
                    echo '1-';
                    return true;
                } else if (!empty($node['nodes'])) {
                    if (breadcrumb($node['nodes'], $needle, $result)){
                    echo '2-';
                    $result[] = $node['title'];
                    return true;
                    }
                }
            }
        } else {
            if ($tree == $needle) {
                echo '3-';
                $result[] = $tree;
                return true;
            }
        }
        return false;
    }
    
    breadcrumb($array, 'item1_sub3_company3', $result);
    
    print_r($result);
    

    The breadcrumb is inverted but you could use array_shift instead of push and you would have it the right way...

    0 讨论(0)
提交回复
热议问题