0

I am working on a script that lets the user load a remote XML file and lets them choose an element. I then need to be able to retrieve the value of that element a later date. The XML is updated regularly and I want to display the updates value each time.

So far I convert the XML into a multidimensional array, display the elements and their values to the user, and when they choose an element I save the keys of the multidimensional array.

So for example if we have the following array:

  Array
(
    [responsecode] => 0
    [message] => 
    [items] => Array
        (
            [0] => Array
                (
                    [title] => Example1
                    [content] => This is the first message
                    [date] => 00/00/00
                )

            [1] => Array
                (
                    [title] => Example2
                    [content] => This is the second message
                    [date] => 00/00/00
                )
       )
)

If the user chooses the first title element I save the path as follows:

$path = "itmes>0>title";

I then explode the string to get the separate keys:

$keys = explode(">", $path);

Array
    (
        [0] => items
        [1] => 0
        [2] => title
    )

If I wanted to read the value manually I would use:

array['items']['0']['title']

But how would I build that query when I have an array of they keys?

1 Answer 1

2

Just write a loop:

function extract_value(array $array, array $keys) {
    foreach($keys as $key) {
        if (!isset($array[$key])) return null;
        $array = $array[$key];
    }

    return $array;
}

You would use this as in

$result = extract_value($data, $keys);

The idea is that you have a variable that "points to" an element in the array, and you update it by branching with each key value. When there are no more keys the pointer points to your result.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.