3

我在这些对象中获取数组时遇到了一些问题。当我 print_r() 时,会打印以下代码。$message_object 是对象的名称。

SimpleXMLElement Object
(
    [header] => SimpleXMLElement Object
        (
            [responsetime] => 2012-12-22T14:10:09+00:00
        )

    [data] => SimpleXMLElement Object
        (
            [id] => Array
                (
                    [0] => 65233
                    [1] => 65234
                )

            [account] => Array
                (
                    [0] => 20992
                    [1] => 20992
                )

            [shortcode] => Array
                (
                    [0] => 3255
                    [1] => 3255
                )

            [received] => Array
                (
                    [0] => 2012-12-22T11:04:30+00:00
                    [1] => 2012-12-22T11:31:08+00:00
                )

            [from] => Array
                (
                    [0] => 6121843347
                    [1] => 6121820166
                )

            [cnt] => Array
                (
                    [0] => 24
                    [1] => 25
                )

            [message] => Array
                (
                    [0] => Go tramping wellington 11-30
                    [1] => Go drinking Matakana 2pm
                )

        )

)

我正在尝试使用 foreach 从对象中获取 id 数组:

foreach($message_object->data->id AS $id) {
    print_r($id);
}

发送以下回复:

SimpleXMLElement Object ( [0] => 65233 ) SimpleXMLElement Object ( [0] => 65234 )

我如何获得 [0] 的值,还是我要解决这个问题?有没有办法循环遍历结果并获取对象键?

我试图回显 $id[0] 但它没有返回任何结果。

4

3 回答 3

4

当你print_r在 a上使用时SimpleXMLElement,两者之间会出现魔法。所以你看到的并不是实际存在的。它提供了丰富的信息,但与普通对象或数组不同。

要回答您的问题如何迭代:

foreach ($message_object->data->id as $id)
{
    echo $id, "\n";
}

回答如何将它们转换为数组:

$ids = iterator_to_array($message_object->data->id, 0);

因为这仍然会为您提供,SimpleXMLElements但您可能希望拥有可以在使用时将这些元素中的每一个转换为字符串的值,例如:

echo (string) $ids[1]; # output second id 65234

或将整个数组转换为字符串:

$ids = array_map('strval', iterator_to_array($message_object->data->id, 0));

或者转换成整数:

$ids = array_map('intval', iterator_to_array($message_object->data->id, 0));
于 2012-12-22T02:54:23.123 回答
1

您可以像这样转换 SimpleXMLElement 对象:

foreach ($message_object->data->id AS $id) {
    echo (string)$id, PHP_EOL;
    echo (int)$id, PHP_EOL; // should work too

    // hakre told me that this will work too ;-)
    echo $id, PHP_EOL;
}

或者投射整个事情:

$ids = array_map('intval', $message_object->data->id);
print_r($ids);

更新

好的,array_map上面的代码实际上并不能正常工作,因为它不是严格意义上的数组,你应该iterator_to_array($message_object->data_id, false)先申请:

$ids = array_map('intval', iterator_to_array$message_object->data->id, false));

另请参阅:@hakre 的答案

于 2012-12-22T02:51:14.440 回答
0

你只需要像这样更新你的 foreach :

foreach($message_object->data->id as $key => $value) {
    print_r($value);
}
于 2012-12-22T02:36:57.030 回答