2017-09-11 23 views
1

多维数组从XML文件Iter项目通过PHP

<items> 
    <item type="blue" /> 
    <item type="red" /> 
    <item type="blue" /> 
    <item type="red" /> 
    <item type="blue" /> 
    <item type="red" /> 
    <item type="blue" /> 
    <item type="red" /> 
    <item type="blue" /> 
    <item type="red" /> 
    <item type="blue" /> 
    <item type="red" /> 
</items> 

我通过了SimpleXML得到下面的数组:

object(SimpleXMLElement)#1 (1) { 
["item"]=> array(12) { 

    [0]=> object(SimpleXMLElement)#2 (1) { 
     ["@attributes"]=> array(1) { 
      ["type"]=> string(4) "blue" 
     } 
    } 

    [1]=> object(SimpleXMLElement)#3 (1) { 
     ["@attributes"]=> array(1) { 
      ["type"]=> string(3) "red" 
     } 
    } 

    [2]=> object(SimpleXMLElement)#4 (1) { … } 
    [3]=> object(SimpleXMLElement)#5 (1) { … } 
    [4]=> object(SimpleXMLElement)#6 (1) { … } 
    [5]=> object(SimpleXMLElement)#7 (1) { … } 
    [6]=> object(SimpleXMLElement)#8 (1) { … } 
    [7]=> object(SimpleXMLElement)#9 (1) { … } 
    [8]=> object(SimpleXMLElement)#10 (1) { … } 
    [9]=> object(SimpleXMLElement)#11 (1) { … } 
    [10]=> object(SimpleXMLElement)#12 (1) { … } 
    [10]=> object(SimpleXMLElement)#12 (1) { … } 
    [11]=> object(SimpleXMLElement)#13 (1) { … } 
} } 

我想通过全项环和选择的前三个与蓝色的类型:

1) Iter through all items 
2) Check whether type == 'blue' 
3) If yes, append the whole item-structure to another array or echo something 

我这样做了很多与Python,哪里可以在所解析的对象导航(一个字典阵列)以k现在只不过是XML的基本结构。但在PHP中,我不明白阵列中的元素是如何处理的。

当我在这里看教程或其他问题时,在我看来,没有像xpath这样的路径系统。我还没有找到像我这样的basix例子。

+0

这是一个重复:SimpleXML的:选择具有一定属性值的元素(https://stackoverflow.com/questions/992450/simplexml-selecting-elements-which-have-a-certain-attribute-value) –

回答

1

你可以这样做

$finalArray = []; 
foreach($var['items'] as $item) 
{ 
if($item['@attributes']['type'] === 'blue') 
    { 
     $finalArray[] = $item; 
    } 
//check if you have 3 items already on the new array so that it will stop the loop 
if(count($finalArray) == 3){ 
return $finalArray; 
} 

}

+0

或者,你可以使用类似于'for($ i = 0; $ i <$ count && count($ finalArray)<3; $我++)'这将使循环更紧凑。我也不喜欢有意想不到的'return'中间函数,特别是循环,imho'break'会更合适。 –

+0

但我认为这会减慢这个过程,因为它会再次循环来检查数组 – pinoyCoder

+0

中的项目是否正确,'count()'可能是一个相当昂贵的函数,但在这种情况下,它是微不足道的我们知道这样的事实,它会始终空着,并停止少量运行 –