开发者

Translate a string with point separated into array keys

I have an string (like one.two.three or month.2) and I need to translate this string exploding point character into array keys.

So I have month.2 and I need the codeline to translate this string into $lang['month'][2]

I was looking for that solution but I am not able to find it, I am blocked.


I finally found this:

<?php
$lang['one']['two']['three'] = 'well done';

$str = 'one.two.three';
$list = explode('.', $str);
$result = '$lang';
foreach ($list as $item)
{
    $result .= '["'.$item.'"]';
}

var_dump(eva开发者_开发百科l("return " . $result.';'));
?>


Start by exploding it:

$in = explode('.', $in);

Then rewrite it as a nested array:

$arg = array();
foreach (array_reverse($in) as $key) {
   $arg = array($key => $arg);
}

And finally merge:

$out = array_merge_recursive($arg, $out);

Edit: in case you're seeking to read the array instead, then bazmegakapa's answer is what you're looking for.


I wrote a little recursive function to handle this. First you explode the string, and pass the array ($lang in your example, $a in mine) and this exploded array to GetVal(). It will do its best to return the needed value into $x.

$s="month.2";
$keys=explode('.', $s);
$a=array(
    'month' => array('1' => 'fos', '2' => 'fos2'),
    'retek' => 1
);

function GetVal($array, $keyarray) {
    $key=array_shift($keyarray);
    if (array_key_exists($key, $array)) {
        if (count($keyarray)==0) {
            return $array[$key];
        } else {
            return GetVal($array[$key], $keyarray);
        }
    } else {
        return null;
    }
}

$x=GetVal($a, $keys);
var_dump($x);


Its a clarification for the use of explode function:

<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>

this code explodes as:

Array
(
[0] => Hello
[1] => world.
[2] => It's
[3] => a
[4] => beautiful
[5] => day.
)

not as Array[hello][world][its][a].......

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜