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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据