【问题标题】:Get array in object xml (simplexml_load_string)获取对象 xml 中的数组(simplexml_load_string)
【发布时间】:2019-09-24 02:47:30
【问题描述】:

我有一个$xml,看起来像这样

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [Total] => 450
            [Count] => 4
            [Start] => 0
        )

    [Code] => 0
    [Item] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [Person.P_Id] => 14845
                )

            [1] => SimpleXMLElement Object
                (
                    [Person.P_Id] => 14844
                )

            [2] => SimpleXMLElement Object
                (
                    [Person.P_Id] => 14837
                )

            [3] => SimpleXMLElement Object
                (
                    [Person.P_Id] => 14836
                )

        )
)

现在我想让数组Item 与另一个数组合并,但是当我尝试$xml->Item 时,我只得到了这个数组的第一个元素(即14845)。当我使用count($xml->Item) 时,它返回真值(即 4)。我是不是做错了什么来获取整个数组Item

【问题讨论】:

  • 你需要迭代->Item,代码在哪里?您忘记在帖子中添加它们

标签: php arrays xml simplexml


【解决方案1】:

您没有说是否要将项目作为 SimpleXMLElements,或者只是 Person.P_Id 值。要获取对象,可以使用xpath 获取数组:

$itemobjs = $xml->xpath('//Item');
print_r($itemobjs);

输出:

Array
(
    [0] => SimpleXMLElement Object
        (
            [Person.P_Id] => 14845
        )    
    [1] => SimpleXMLElement Object
        (
            [Person.P_Id] => 14844
        )    
    [2] => SimpleXMLElement Object
        (
            [Person.P_Id] => 14837
        )    
    [3] => SimpleXMLElement Object
        (
            [Person.P_Id] => 14836
        )    
)

如果您只需要 Person.P_Id 值,则可以使用 array_map 迭代该数组:

$items = array_map(function ($v) { return (string)$v->{'Person.P_Id'}; }, $itemobjs);
print_r($items);

输出:

Array
(
    [0] => 14845
    [1] => 14844
    [2] => 14837
    [3] => 14836
)

Demo on 3v4l.org

【讨论】:

  • 感谢您的回答,这就是我想要的$itemobjs = $xml->xpath('//Item');
  • @LuuHoangBac 不用担心。我很高兴能帮上忙。
  • 我还有一个问题,我想知道这是否很难。我想将另一个数组(格式相同)分配给$xml->Item 数组,可以吗?作为普通代码,我会做这样的事情$xml->Item = $new_array,但在这种情况下,我不能
  • 您的意思是要替换数组中的项目吗?这在 SimpleXML 中是不可能的,但您可以使用 DOM 来实现。请参阅此问答:stackoverflow.com/questions/17661167/…
  • 如果您在实现该代码时遇到问题,请写一个新问题(参考那个问题)。
猜你喜欢
  • 1970-01-01
  • 2011-04-16
  • 2023-03-29
  • 2012-12-30
  • 2014-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多