1
$lookup_table = array ("a" => "['foo']['bar']", "b" => "['foo']['man'][0]");

$foo = array ("a" => array ("bar" => "my value"));

var_dump ($foo['a']['bar']); //output: my value

What I want to do is put ['a']['bar'] as a string and basically make a little array that holds a key and the value or location in the array where the value would be.

$key = "['a']['bar']"; and then do $x = $foo[$key]; and have $x = "my value".

I realize I already put square brackets in the string and I'm doing it again above but I'm not sure how I would write it in the string.

6
  • You want to assign value to key as you did in foreach loop? this much or or anything else also? Commented May 9, 2015 at 19:07
  • @anantkumarsingh I want $x = "my value" when I do $x = $foo[$lookup_table[$a]]; but I can't use the array key as a string like I did Commented May 9, 2015 at 19:09
  • What is your expected output . write in your code. Your question is not going to clear me. And please put your output based on array that you show initially not like $x = 'my vale' and all that? Commented May 9, 2015 at 19:12
  • There are a couple of complicated ways to traverse the target array using such path descriptors. And one lazy approach - depending on usage context. Commented May 9, 2015 at 19:16
  • @anantkumarsingh - I rewrote my question to be hopefully be easier to understand Commented May 9, 2015 at 19:26

1 Answer 1

0
$lookup_table = array ("a" => "['foo']['bar']", "b" => "['foo']['man'][0]");
$foo = array ("a" => array ("bar" => "my value"), "b" => array("man" => array("blah")));

echo getValue($lookup_table, $foo);

echo "\n";



function getValue($lookup, $source)
{
    foreach ($lookup as $k => $v)
    {
        $v = str_replace("'", "", $v);
        $v = ltrim(rtrim($v, "]"), "[");

        $values = explode("][", $v);
        $data = $source[$k];

        for ($i = 1; $i < count($values); $i++) 
        { 
            $data = $data[$values[$i]];

            if($i == (count($values) - 1))
                echo $k . " = " . $data . "\n";
        }
    }
}

Output:

a = my value
b = blah

I don't think you need to use the ' because you kind of declaring the key .. so the function can just use it as int and string the same.

So, basically what I did is: 1. Looping thought all the keys with the formatted arrays. 2. Skipping the first one because its the actual variable name 3. Looping until we reach the final value and then we display it.

Btw, do wanted to actually find the $foo as well ? if yes. let me know and I'll edit the code.

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.