Jump to content

Select value from a multidimensional array using a delimited string?


Recommended Posts

Hey everyone! Bit stuck here. Not sure if I'm thinking about this too much or whether it's just insanely hard. Basically I want to return a value from a multidimensional array based off of a string with delimiters.

 

Probably easier to show you than to explain:

 

$str = 'str1.str2.str3';

$array = array(
    'str1' => array(
        'str2' => array(
            'str3' => 'I want to return this...',
        ),
    ),
);

 

So using $str I want to traverse through the array to return 'I want to return this...'

 

Any body have any ideas? I'm pretty stumped!

 

Thanks in advance,

Adam

something along these lines should work.  You just keep capturing a pointer to the element of interest until you have traversed the entire list of keys. 

$str = 'str1.str2.str3';

$array = array(
    'str1' => array(
        'str2' => array(
            'str3' => 'I want to return this...',
        ),
    ),
);

$keys = explode ($str, "."); // or is it explode(".", $str)?  I can never remember
$hold = &$array;
foreach ($keys as $key) {
  $hold = &$hold[$key];
}

// $hold now points to the field you are looking for

 

Watchout though.  If $str starts out as "str1.str2" you will end up with $hold referencing $array[str1][str2] which is an array NOT a string value.

 

Thanks for that DavidAM. I actually managed to solve it in a slightly different way using a recursive function:

 

    public function get($property)
    {
        $tokens = explode('.', $property);
        $return = $this->properties;

        foreach ($tokens as $token)
        {
            $return = $this->recurseGet($token, $return);

            if (!$return)
            {
                break;
            }
        }

        return $return;
    }

    protected function recurseGet($token, $properties)
    {
        if (array_key_exists($token, $properties))
        {
            return $properties[$token];
        }

        return false;
    }

 

Thanks anyway though, much appreciated!

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.