plist simpleXML,访问数组列表时遇到问题


plist simpleXML, trouble accessing array list

假设我有一个plist simplexml文档,看起来像这样:

<dict>
<key>UIRequiredDeviceCapabilities</key>
<array>
    <string>armv7</string>
</array>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationPortraitUpsideDown</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array>

我可以像这样访问字符串:

$obj->dict->string[0]

这将为我返回 6.0。但是,如果我想访问第二个数组中的第一个字符串:

$obj->dict->array[1]->string[0]

PHP 抛出一个错误,不喜欢我对数组的引用。这里的正确语法是什么?苹果列表单面文档上的例子并不多。谢谢。

因为array是一个PHP关键字,所以尝试在该上下文中使用它将是一个语法错误。 你需要做的是把它包装为{}中的带引号的字符串,有效地将其转换为动态属性名称。

// Using the {"string"} dynamic property syntax:
echo $obj->dict->{'array'}[1]->string[0]
// Prints UIInterfaceOrientationPortrait

这在 PHP 的变量变量和变量属性语法参考中记录得很模糊。

与避免使用关键字相比,您可以使用它来动态构造字符串形式的属性。它很方便,但不是那么出名。

// More often used to build properties or method names as strings...
///...Not that you need to do this...
$v1 = "arr";
$v2 = "ay";
echo $obj->dict->{$v1 . $v2}[1]->string[0];