duanmei1930 2018-08-11 15:37
浏览 151
已采纳

从嵌套的关联数组中获取单个值

For a setup script I write in PHP (for CLI, not web) I use a settings file as well as other other "content" files.

The settings file is built up like a regular ini-file

[header.subheader.moreheaders...]
keyA = value
keyB = value1|value2|...

"header.subheader.moreheaders..." and "keyX" will form a nested associative array with "value" as a string or "value1|value2|..." as a simple array (0-...).

Thanks to this accepted answer, I got so far that I can split the headers into a recursive array recursively. So far, so good.

However, as the content files shall contain references to these variables, I would like to be able to read out single values from that multi-dimensional array with string placeholders like $@R[header.subheader.moreheaders.key] or $@R[header.subheader.moreheaders.key.0] depending on them being a string or an array.

In the script, $@R[header.subheader.moreheaders.key.0] should convert into $SettingsVar[header][subheader][moreheaders][key][0] to return the appropriate value.

Neither the script nor the content files will know what is inside the settings file. The script just knows the general structure and placeholder $@R[...].

This answer appears to know what value will be in order to search for it.

Since I do not fully understand this answer, I am not sure if that would be the right way.

Is there a similar easy way to get the reverse from building that array?

  • 写回答

1条回答 默认 最新

  • doushang4274 2018-08-12 11:42
    关注

    After some contemplation, I found a decent enough solution, which works for me (and hopefully others):

    function GetNestedValue($aNestedKeys, $aNestedArray)
    {
        $vValue = $aNestedArray;
        for($i = 0; $i < count($aNestedKeys); $i++)
        {
            if(array_key_exists($aNestedKeys[$i], $vValue))
            {
                $vValue = $vValue[$aNestedKeys[$i]];
            }
            else
            {
                $vValue = null;
                break;
            }
        }
    
        return $vValue;
    }
    

    Depending on what $aNestedKeys contain, it will either return a sub-array from $aNestedArray, a single value from it or null if any of the specified keys were not found.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名