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.

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

报告相同问题?

悬赏问题

  • ¥20 access中怎么分割分别获取一下图中的值
  • ¥15 keras_tcn已经安装成功,还是显示ModuleNotFoundError: No module named 'keras_tcn'
  • ¥15 类图中关联与聚合的区别
  • ¥15 ENVI高分五号去除云层的方法
  • ¥15 16进制数据如何得到奇偶校验位
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题