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

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

WBOY
Release: 2016-06-06 20:14:35
Original
1208 people have browsed it

如:

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

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

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

</code>
Copy after login
Copy after login

谢谢.

回复内容:

如:

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

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

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

</code>
Copy after login
Copy after login

谢谢.

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

你想要的可能是

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

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

是这样吗?

修改答案

<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>
Copy after login

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

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

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template