从嵌套的关联数组中获取单个值
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?
对于我用PHP编写的设置脚本(对于CLI,而不是Web)我使用设置文件以及其他 其他“内容”文件。 p>
设置文件就像常规的ini文件 p>
[header.subheader.moreheaders。 ..]
keyA = value
keyB = value1 | value2 | ...
code> pre>
“header.subheader.moreheaders ...”和“keyX”将形成 一个嵌套的关联数组,其中“value”为字符串,“value1 | value2 | ...”为简单数组(0 -...)。 p>
感谢这个已接受的答案,到目前为止,我可以递归地将标题拆分为递归数组。 到目前为止,非常好。 p>
但是,由于内容文件应包含对这些变量的引用,我希望能够使用字符串占位符从该多维数组中读出单个值 喜欢 $ @ R [header.subheader.moreheaders.key] code>或 $ @ R [header.subheader.moreheaders.key.0] code>,具体取决于它们是字符串还是 数组。 p>
在脚本中, $ @ R [header.subheader.moreheaders.key.0] code>应转换为 $ SettingsVar [header] [ subheader] [moreheaders] [key] [0] code>返回适当的值。 p>
脚本和内容文件都不知道设置文件中的内容。 该脚本只知道一般结构和占位符 $ @ R [...] code>。 p>
这个答案似乎知道搜索它会有什么价值。 p>
因为我不完全理解这个答案,我不确定这是不是正确的方法。 p>
是否有类似的简单方法 从构建该数组获得相反的结果? p>
div>
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.