0

如何访问这个关联数组?

Array
(
    [order-id] => Array
       (
           [0] => 1
           [1] => 2
       )

)

作为 XML 解析的结果

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE request SYSTEM "http://shits.com/wtf.dtd">
<request version="0.5">
<order-states-request>
    <order-ids>
        <order-id>1</order-id>
        <order-id>2</order-id>
          ...
    </order-ids>
 </order-states-request>
</request>


$body = file_get_contents('php://input');
$xml = simplexml_load_string($body);

$src = $xml->{'order-states-request'}->{'order-ids'};
foreach ($src as $order) {
     echo ' ID:'.$order->{'order-id'};

// 不工作 - 只回显 ID:1,为什么?}

// 好吧,让我们尝试另一种方式...

$items = toArray($src); //googled function - see at the bottom
print_r($items);

// 打印结果 - 参见 assoc 数组的顶部

// 以及如何在这个 (fck) assoc 数组中访问订单 ID???

//------------------------------------------------------

function toArray(SimpleXMLElement $xml) {
    $array = (array)$xml;

    foreach ( array_slice($array, 0) as $key => $value ) {
        if ( $value instanceof SimpleXMLElement ) {
            $array[$key] = empty($value) ? NULL : toArray($value);
        }
    }
    return $array;
}

非常感谢您的帮助!

4

1 回答 1

1

你想要的是:

$body = file_get_contents('php://input');
$xml = simplexml_load_string($body);
$src = $xml->{'order-states-request'}->{'order-ids'}->{'order-id'};
foreach ($src as $id)
{
     echo ' ID:', $id, "\n";
}

现场演示。

你的代码会发生什么是你试图循环:

$xml->{'order-states-request'}->{'order-ids'}

正如您在转储中看到的那样,这不是array您想要的:order-id

Array
(
    [order-id] => Array
于 2013-08-28T23:17:41.213 回答