doucao1066 2015-05-09 18:54
浏览 80

将字符串用于多维数组键

$lookup_table = array ("a" => "['foo']['bar']", "b" => "['foo']['man'][0]");

$foo = array ("a" => array ("bar" => "my value"));

var_dump ($foo['a']['bar']); //output: my value

What I want to do is put ['a']['bar'] as a string and basically make a little array that holds a key and the value or location in the array where the value would be.

$key = "['a']['bar']"; and then do $x = $foo[$key]; and have $x = "my value".

I realize I already put square brackets in the string and I'm doing it again above but I'm not sure how I would write it in the string.

  • 写回答

1条回答 默认 最新

  • dounao2829 2015-05-09 19:46
    关注
    $lookup_table = array ("a" => "['foo']['bar']", "b" => "['foo']['man'][0]");
    $foo = array ("a" => array ("bar" => "my value"), "b" => array("man" => array("blah")));
    
    echo getValue($lookup_table, $foo);
    
    echo "
    ";
    
    
    
    function getValue($lookup, $source)
    {
        foreach ($lookup as $k => $v)
        {
            $v = str_replace("'", "", $v);
            $v = ltrim(rtrim($v, "]"), "[");
    
            $values = explode("][", $v);
            $data = $source[$k];
    
            for ($i = 1; $i < count($values); $i++) 
            { 
                $data = $data[$values[$i]];
    
                if($i == (count($values) - 1))
                    echo $k . " = " . $data . "
    ";
            }
        }
    }
    

    Output:

    a = my value
    b = blah
    

    I don't think you need to use the ' because you kind of declaring the key .. so the function can just use it as int and string the same.

    So, basically what I did is: 1. Looping thought all the keys with the formatted arrays. 2. Skipping the first one because its the actual variable name 3. Looping until we reach the final value and then we display it.

    Btw, do wanted to actually find the $foo as well ? if yes. let me know and I'll edit the code.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大