PHP中的$$数组变量

时间:2015-05-29 12:58:45

标签: php reference

我可以使用$$变量来引用像这样的变量

$var = 'car';
$car = 'Lamborghini';
echo $$var;

以上代码将回显兰博基尼

但是我有这样的代码: -

$var = "['acct_1']['etc']['anotherInfo']['sing']";
$var = 'arr'.$var;
echo $arr['acct_1']['etc']['anotherInfo']['sing'] ;
echo $$var;

第一个echo打印正确的值,但$$ var没有给出正确的值。

非常感谢任何帮助。

由于

2 个答案:

答案 0 :(得分:2)

您始终可以将密钥保存在数组中,然后对其进行迭代以正确解析值:

$keys = ['acct_1', 'etc', 'anotherInfo', 'sing'];

$val = $arr;
foreach($keys as $key) {
    $val = $val[$key];
}

现在,$arr['acct_1']['etc']['anotherInfo']['sing']$val都具有相同的值。

this demo中试用。

修改

您已在$keys中拥有$indexInfo数组。您应该可以这样使用它:

function replaceValue($arr, $indexInfo, $char)
{
    // $indexInfo is all you need!
    $var = $arr;
    foreach($indexInfo as $key) {
        $var = $var[$key];
    }
    echo $arr['acct_1']['etc']['anotherInfo']['sing'] . "\n";
    echo $var  . "\n";
    die($var);
}

答案 1 :(得分:1)

不幸的是,这不起作用,但为什么不做这个行

/**
 * Search into a multi dimensional array to find arbitrary data
 * @param array $array The array to search
 * @param string ... Any number of array keys
 * @return mixed
 */
function deepArraySearch(array $array) {
    $keys = func_get_args();
    array_shift($keys); // First element is the array

    // If no more keys to use
    if(!$keys) {
        return $array;
    }

    $nextKey = array_shift($keys);
    $nextData = $array[$nextKey];

    // Nothing left to search
    if(!is_array($nextData )) {
        return $nextData ;
    }

    array_unshift($keys, $nextData);
    return call_user_func_array('deepArraySearch', $keys);
}

$arr = ['one' => ['two' => ['three' => 'data']]];

print_r(deepArraySearch($arr, 'one'));
print_r(deepArraySearch($arr, 'one', 'two'));
print_r(deepArraySearch($arr, 'one', 'two', 'three'));

echo PHP_EOL;

在你的情况下,我猜它会像这样工作

$arr = ['acct_1' => ['etc' => ['anotherInfo' => ['sing' => 'song']]]];
print_r(deepArraySearch($arr, 'acct_1', 'etc', 'anotherInfo', 'sing')); // song

最后说明:

如果您使用的是PHP 5.6,7或HHVM,则此功能更好:

<?php

/**
 * Search into a multi dimensional array to find arbitrary data
 * @param array $array The array to search
 * @param string ... Any number of array keys
 * @return mixed
 */
function deepArraySearch(array $array, ...$keys) {

    // If no more keys to use
    if(!$keys) {
        return $array;
    }

    $nextKey = array_shift($keys);
    $nextData = $array[$nextKey];

    // Nothing left to search
    if(!is_array($nextData )) {
        return $nextData ;
    }

    return deepArraySearch($nextData, ...$keys);
}

演示:http://3v4l.org/vmocO