On 11-12-14 01:11 AM, Laruence wrote:
On Wed, Dec 14, 2011 at 9:27 AM, Nils Leideck<nils.leid...@leidex.net>  wrote:
Hi Al,

many thanks for your feedback. Unfortunately I don’t know the deepness of the 
array so I can’t use the nested foreach() idea :-( Let me try to simplify my 
question (which also helps myself to clarify my process ;-)

I have a variable where the value is a string that is exactly the path to the 
array value:

[code]
    $arrayPath = "['user_interface’][‘design']['my_colors']['item_number_one’]”;
[/code]

And I have an array that has all the details:

[code]
    $myArray = coolFunction(‘getArray’);
[/code]

The question is, how can I use these both informations to return a value from 
the $myArray?

Examples I tried unsuccessfully:

[code]
    [...]
    echo $myArray$arrayPath;
    echo $myArray{$arrayPath};
    echo $myArray${arrayPath};
    echo $myArray${$arrayPath};
    echo $myArray.$arrayPath;
    echo $myArray.$arrayPath;
    [...]
[/code]
    etc...

your feedback is much much much appreciated!!!

Cheers, Nils
--
http://webint.cryptonode.de / a Fractal project

for you quesion, try eval:
<?php
$arr = array("a"=>array("b"=>array("c")));
$key = "['a']'['b]";
$value = eval("return \$arr". $key .";");
?>

ps: your requirement is a little odd :)

If the solution is to use eval() then you've almost certainly come up with the wrong answer.

To get the desired answer you can either use recursion to recursively index the array as necessitated by the "path" or you can use references to incremententally step through the array. Example:

<?php

$path = 'path/to/data/in/my/arbitrarily/deep/array';
$array = $someBigFatArray;

$focus = &$array();
foreach( explode( '/', $path ) as $step )
{
    if( isset( $focus[$step] ) )
    {
        $focus = &$focus[$step];
    }
    else
    {
        unset( $focus );
        $focus = null;
        break;
    }
}

echo $focus;

?>

You can wrap this puppy in a function too... and it will be faster than the recursive version someone else wrote because it doesn't incur the overhead of multiple function calls (for depths greater than 1).

Recursion is great, recursion is elegant, computer science professors love recursion, but it can also be a resource pig and PHP doesn't do tail recursion :)

Cheers,
Rob.
--
E-Mail Disclaimer: Information contained in this message and any
attached documents is considered confidential and legally protected.
This message is intended solely for the addressee(s). Disclosure,
copying, and distribution are prohibited unless authorized.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to