Tuesday, 23 January 2018

Array get path

With this function you can find values in an array by
an path like "abc/def/ghi".
This function was an idea, I had a few months ago...

function ArrayGetPath($data, $path, &$result){

    $found = true;

    $path = explode("/", $path);

    for ($x=0; ($x < count($path) and $found); $x++){

        $key = $path[$x];

        if (isset($data[$key])){
            $data = $data[$key];
        }       
        else { $found = false; }
    }

    $result = $data;

    return $found;
}

// Please look at the examples (below)

// test data:

$tree_data = array(
    'red' => array(
        'max' => 100,
        'min' => 0
    ),
    'blue' => 'water',
    'green' => 'flowers',
    'grey' => array(
        'light' => array('eeeeee', 'e7e7e7'),
        'dark' => array('cccccc')
    ),
    7 => 'foobar'
);


// path tests:

$path_tests = array(
    'red/max',
    'foo/bar',
    'grey/light/1',
    'grey/dark',
    'grey/dark/1',
    'red/min',
    'red/min/1',
    'abc/def/ghi',
    '7',
    'grey'
);


// loop trough all path tests:
for ($x=0; $x < count($path_tests); $x++){

    $test_path = $path_tests[$x];

    // test path:
    if(ArrayGetPath($tree_data, $test_path, $result)){
        print "The array path '$test_path' was found, showing content:<br/>\n<pre>";
        print_r($result);
        print "</pre>";
    }
    else { print "The array path '$test_path' was not found!<br/>\n"; }

    print "<br/>\n";

}

0 comments:

Post a Comment