0

我正在使用从 XML 文件转换的多维 PHP 数组,并且正在努力从所有键名中获取特定属性(我不知道所有键的名称,但它们都具有相同的属性。 )

"$player_stats" 中的每个 Key 在数组中的结构如下:

[RandomKeyName] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [assists] => 0.10
                [rebounds] => 8
                [operator] => >
                [overall] => 1.45
            )

    )

我正在尝试实现以下目标。使用 $key => $value 时,我无法从键中获取属性吗?

foreach ($player_stats as $key => $value) {

    $rebounds = $key->rebounds;
    $assists = $key->assists;

    echo "$key has $rebounds Rebounds and $assists Assists. <br>";
}

$key 在此示例中有效,但我尝试抓取的属性无效。在不知道键名的情况下获取所有键的特定属性的任何提示或指针都会很棒,谢谢!

编辑:

我试图获取以下关键对象的 XML 部分:

<Player_Stats>
  <RandomKeyName1 assists="0.04" rebounds="9" operator="&gt;" overall="0.78" />
  <RandomKeyName2 assists="0.04" rebounds="4" operator="&gt;" overall="2.07" />
  <RandomKeyName3 assists="0.04" rebounds="1" operator="&gt;" overall="3.76" />
  <RandomKeyName4 assists="0.04" rebounds="10" operator="&gt;" overall="0.06" />
</Player_Stats>
4

1 回答 1

0

如果我理解正确的话,$value 是一个 SimpleXMLElement 对象。您可以使用SimpleXMLElement::attributes获取属性,您可以使用另一个 foreach 对其进行迭代。

看起来像这样(尽管我自己没有测试过)。

foreach ($player_stats as $xmlKey => $xmlElement) {

    foreach ($xmlElement->attributes() as $attrKey => $value) {

        if ($attrKey === 'rebounds')
            $rebounds = $value;

        if ($attrKey === 'assists')
            $assists = $value;

    }
    echo "$xmlKey has $rebounds Rebounds and $assists Assists. <br>";
}
于 2013-03-26T03:43:31.807 回答