Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My question is similar to Searching for an array key branch inside a larger array tree - PHP, but for different limitations (like processing on the fly, etc) and why not for knowledge sake I would like to implement it using just PHP recursion.

Consider this data:

array(
    'root_trrreeee1' => array(
        'path1' => array(
            'description' => 'etc',
            'child_of_path_1' => array(
                array('name' => '1'),
                array('name' => '1')
            )
        ),
        'path1' => array(
            'description' => 'etc',
            'child_of_path_1' => array(
                array('name' => '1'),
                array('name' => '1')
            )
        ),
    ),
    'name' => '1',
    1 => array('name' => '1'),
    'another_leaf' => '1'
)

If I search for array('name' => '1') it should return the path I need to traverse to get to that value root_trrreeee1.path1.child_of_path_1.o, preferably returned as array:

array(
    0 => root_trrreeee1
    1 => path1
    2 => child_of_path_1
    3 => 0
)

This is the recursive function I've tried to implement but its not working:

function multidimensional_preserv_key_search($haystack, $needle, $path = array(), &$true_path = array())
{
    if (empty($needle) || empty($haystack)) {
        return false;
    }

    foreach ($haystack as $key => $value) {

        foreach ($needle as $skey => $svalue) {

            if (is_array($value)) {
                $path = multidimensional_preserv_key_search($value, $needle, array($key => $path), $true_path);
            }

            if (($value === $svalue) && ($key === $skey)) {
                $true_path = $path;
                return $true_path;
            }
        }

    }

    if (is_array($true_path)) { return array_reverse(flatten_keys($true_path)); }
    return $path;
}


function flatten_keys($array)
{
    $result = array();

    foreach($array as $key => $value) {
        if(is_array($value)) {
            $result[] = $key;
            $result = array_merge($result, self::flatten_keys($value));
        } else {
            $result[] = $key;
        }
    }

    return $result;
}

it returns just an empty array. Thanks in advance.

Similar questions I've found:

share|improve this question
add comment

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.