Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic search through a Array

Tags:

arrays

php

I'm running into a dilemma, i'm trying to create a function to "dynamically" search trough an array, in this case my session array, but it should be for any. Now that is not my problem, my problem is to dynamically allow this to be done...

Here's what i have

public static function get($search = 'First/Second/Third') {    
    $explode = explode('/',$search);
    $count = count($explode);
    if ($count == 1)
        if (isset($_SESSION[$explode[0]]))
            return $_SESSION[$explode[0]];
    elseif ($count == 2)
        if (isset($_SESSION[$explode[0]][$explode[1]]))
            return $_SESSION[$explode[0]][$explode[1]];
    elseif ($count == 3)
        if (isset($_SESSION[$explode[0]][$explode[1]][$explode[2]]))
            return $_SESSION[$explode[0]][$explode[1]][$explode[2]];
}

So let's say i have an array:

 array('First' => array('Second' => array('Third' => 'TEST VALUE'));

Now i want to call

$value = get('First/Second/Third');

and then get "Test Value" back as the value for my $value variable.

In this situation it works, but it just isn't dynamic, and I want it to be able to handle maybe even a 10 layer deep array as well, without adding more and more lines....

Well maybe someone out here smarter then me :)

Thanks!!

like image 244
Tobias Hagenbeek Avatar asked Jun 04 '13 19:06

Tobias Hagenbeek


2 Answers

$array = array(
        'First' => array(
                'Second' => array(
                        'Third' => 'TEST VALUE'
                )
        )
);
echo get($array, 'First/Second/Third'); //  TEST VALUE

Function Used

function get($data, $part) {
    foreach(explode("/", $part) as $key) {
        $data = isset($data[$key]) ? $data[$key] : null;
    }
    return $data;
}

Live Demo

like image 72
Baba Avatar answered Oct 08 '22 00:10

Baba


Something like this:

$data = $_SESSION;
foreach(explode('/', $seach) => $pos) {
    $data = $data[$pos];
}
return $data;
like image 26
mzedeler Avatar answered Oct 08 '22 02:10

mzedeler