Mario E Moreno
Mario E Moreno

Reputation: 1

XML to array - Group Array results based on one child element

I have a XML which I converted to array without a problem, the original XML looks something like this.

<somedata>data</somedata>
<somedata2>data2</somedata2>
<level1>
   <listings>
     <element>
        <title>AAA</title>
        <description>DescriptionA</description>
        <moredata>
          <adate>2012/12/12</adate>
        </moredata>
     </element>

     <element>
        <title>AAA</title>
        <description>DescriptionA</description>
        <moredata>
          <adate>2013/10/12</adate>
        </moredata>
     </element>

     <element>
        <title>BBB</title>
        <description>DescriptionB</description>
        <moredata>
          <adate>2012/09/01</adate>
        </moredata>
     </element>
   </listings>
<level1>

Of course so far everything looks fine, I get my nice array with all the child objects, but I need to create an HTML output by grouping the elements by for example the Title, considering that my Output would look something like this.

Title: AAA
Description: DescriptionA
Date 1: 2012/12/12
Date 2: 2013/10/12

Title: BBB
Description: DescriptionB
Date 1: 2012/09/01

Notice I have grouped AAA which was repeated and listed both dates within the same result.

How in PHP, I was seriously thinking on saving to mysql then pulling them back, but that will simply be a bad patch.

Hope anyone can help.

Regards

Upvotes: 0

Views: 535

Answers (1)

endo.anaconda
endo.anaconda

Reputation: 2468

this is a rough concept how i'd do it.

you have to parse the xml with simplexml into an array, after that you can customize your html output.

$result = array();

foreach($xml->element as $element){

   $line = array();
   $line['date'] = $element->date;
   $line['description'] = $element->description;

   $result[$element->title]['line'][] = $line;

}

Upvotes: 2

Related Questions