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 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目