PHP在嵌套数组/对象中获取值

时间:2015-01-22 17:20:04

标签: php arrays

我试图在此对象(xml)中返回typeName键的值。

[geometricProperty] => Array
    (
        [0] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [typeName] => localizacao  // < - - - This is the value I need.
                    )

                [Point] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [ID] => swrefVgetZredeVcollX757678785
                                [srs] => ut_cm
                            )

                        [coordinates] => 38871,739716 
                    )

            )

        [1] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [typeName] => limite
                    )

                [Polygon] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [ID] => swrefVgeometryV08945038
                                [srs] => utm_23_cm
                            )

                        [outerBoundaryIs] => SimpleXMLElement Object
                            (
                                [LinearRing] => SimpleXMLElement Object
                                    (
                                        [coordinates] => 318950,7399585 31981,39650 31826,73990 316956,79750 
                                    )

                            )

                    )

            )

...

我已经尝试过以下操作,但它返回NULL

echo "<p>This object has ".(count($n->Feature->geometricProperty))." items.</p>";
$c=0;
foreach($n->Feature->geometricProperty as $k){
    $c++;
    echo "<p>$c)".(gettype($k))."</p>";

    foreach(array_keys(get_object_vars($k)) as $o){ 
        echo "<p>$o</p>";

        switch($o){
            case "@attributes": var_dump($k->{$o}["typeName"]); $tipo=$k->{$o}["typeName"]; break;
            case "Point": $value=$k->{$o}->coordinates; break;
            case "Polygon": $value=$k->{$o}->outerBoundaryIs->LinearRing->coordinates; break;
            case "Line...": break;
        }
    }

    echo "<p>TIPO: $tipo</p><p>VALOR: $value</p>";

}

输出:

This object has 3 items.

1)object

@attributes
NULL

Point

TIPO:

VALOR: 31869871,739796106

2)object

@attributes
NULL

Polygon

TIPO: 

搜索并找到this overflow question并且无法猜出我做错了什么。

1 个答案:

答案 0 :(得分:1)

您可以使用SimpleXmlElement::attributes()获取一系列属性。那么你只需循环它们并显示它们或使用implode或其他东西......取决于你想要的输出。