Home >Backend Development >PHP Tutorial >请问php如何快速的根据字符串进行数组访问.

请问php如何快速的根据字符串进行数组访问.

WBOY
WBOYOriginal
2016-06-06 20:14:351207browse

如:

<code>$array=>[
'a'=>[
    'b'=>[
        'name'=>'张三'
    ]
]
];</code>

请问如何实现下方的访问方式.

<code>$arrayNode = ['a','b','name'];
//请问如何根据 $arrayNode 变量来实现
$array{$arrayNode}='李四';//这样php会报错.
// $array['a']['b']['name']='李四';  类似这样的效果呢? 
print($array{$arrayNode});
//李四

</code>

谢谢.

回复内容:

如:

<code>$array=>[
'a'=>[
    'b'=>[
        'name'=>'张三'
    ]
]
];</code>

请问如何实现下方的访问方式.

<code>$arrayNode = ['a','b','name'];
//请问如何根据 $arrayNode 变量来实现
$array{$arrayNode}='李四';//这样php会报错.
// $array['a']['b']['name']='李四';  类似这样的效果呢? 
print($array{$arrayNode});
//李四

</code>

谢谢.

<code>$arrayNode = ['a','b','name'];
$array=[
    'a'=>[
        'b'=>[
            'name'=>'张三'
        ]
    ]
];
echo $array[array_shift($arrayNode)][array_shift($arrayNode)][array_shift($arrayNode)];</code>

你想要的可能是

<code>$arrayNode = ['a','b','name'];

$array[array_shift($arrayNode)][array_shift($arrayNode)][array_shift($arrayNode)] = "李四";</code>

是这样吗?

修改答案

<code><?php $arrayNode = ['a','b','name',"1234"];
$arr = [];
$name = "李四";
while ($arrayNode) {
    if(count($arr)==0){
        $arr[array_pop($arrayNode)] = $name;
    }else{
        $arr[array_pop($arrayNode)] = $arr;
        array_shift($arr);
    }
    
}
var_dump($arr);</code></code>

<code>$pointer = &$array;
$found = true;
foreach ($arrayNode as $key) {
    if (isset($pointer[$key])) {
        $pointer = &$pointer[$key];
    } else {
        $found = false;
        break;
    }
}

if ($found) {
    $pointer = '李四';
}
</code>

长是长了点,不过适应性应该还可以。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn