在数组中获取对象而不是对象属性

时间:2016-03-16 23:00:24

标签: php object

当我按照$sales = $response->xml->transactions设置$ sales时,内容如下:

SimpleXMLElement Object
(
    [transaction] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [transId] => 9999999999
                    [submitTimeUTC] => 2016-03-16T21:57:54Z
                    [submitTimeLocal] => 2016-03-16T14:57:54
                    [transactionStatus] => capturedPendingSettlement
                    [invoiceNumber] => 4b1008a87f5262f0c867
                    [firstName] => Foo
                    [lastName] => Bar
                    [accountType] => Visa
                    [accountNumber] => XXXX1414
                    [settleAmount] => 155.00
                    [marketType] => eCommerce
                    [product] => Card Not Present
                )

            [1] => SimpleXMLElement Object
                (
                    [transId] => 

所以->transaction包含一个数组。但如果我这样做:

   $sales = $response->xml->transactions->transaction;
    foreach ($sales as $s) {
        $list[]= $s->invoiceNumber; 
    }

$ list contains

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => ac502c094fe1722ba100
        )

    [1] => SimpleXMLElement Object
        (
            [0] => e2eb58351c87155e3720
        )

    [2] => SimpleXMLElement Object
        (
            [0] => 0bca2bb6d5a13e641b67
        )

我做错了什么? SimpleXMLElement对象来自我刚想到的invoiceNumber字符串?

1 个答案:

答案 0 :(得分:2)

获取SimpleXMLElement类型对象的原因是因为当您执行$list[]= $s->invoiceNumber;时,您正在按原样添加元素。由于它是SimpleXMLElement对象的一部分,因此它在内部具有该类型。在使用SimpleXML时会出现这种情况,因此请记住这一点。

正如评论casting中所提到的,字符串将只给出值:

$list[] = (string) $s->invoiceNumber;