使用数组或字符串从数组中调用值 - php 我想要一个类似这样的方法:或

问题描述

我在编写可以获取值的代码时遇到问题,但使用文本或数组

假设这个数组:

$array = [
    'name' => 'any Name','settings' => [
            'app' => 'Spy','location' => 'Earth','locale' => 'en'
    ]
];

我想获得 app

代码

echo $array['settings']['app'];

但是这种方法不起作用,因为我无法在我的情况下写括号 [] []

我想要一个类似这样的方法

$handle = 'app,name';
echo $array[$handle] ; 

$handle = ['settings']['app'];

echo $array[$handle];

我知道代码错误的,但举个例子

我希望这个想法已经出现并且有一个解决方案。

解决方法

会是这样吗?

<?php

$array = [
    'name' => 'any Name','settings' => [
            'app' => 'Spy','location' => 'Earth','locale' => 'en'
    ]
];

$str = 'settings|app'; // this is string you have

foreach (explode('|',$str) as $key) {
    if (!isset($output)) {
        $output = $array[$key];
    } else {
        $output = $output[$key];    
    }
}

echo $output; // spy

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...