我在这些对象中获取数组时遇到了一些问题.当我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]但它没有返回任何结果.
解决方法:
当你在SimpleXMLElement上使用print_r时,它们之间会产生魔力.所以你看到的实际上并不是什么.它提供了丰富的信息,但与普通对象或数组不同.
要回答您的问题如何迭代:
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));