Прохождение через многомерный массив в переполнении стека

Из XML-файла

<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, где я могу перемещаться в разобранном объекте (массив dict), не зная ничего, кроме базовой структуры XML. Но в PHP я не понимаю, как элементы в массиве адресуются.

Когда я смотрю на учебники или другие вопросы здесь, мне кажется, что нет такой системы путей, как xpath. Я не нашел такого базового примера, как мой.

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;
}

}

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector