I Have a Parts List Coming from an XML File, It goes something like what is below. I Want to be able to generate using PHP a Combined List. For Example the "Part 1" Is recorded twice. I want the Qty to Show 13 Under Part 1 when Generated either in a JSON output or another XML Output. What would be the best way of doing that? I looked at the php function array_combine but wasn't able to figure out if the values could be combined mathematically instead of showing one of the results. I am loading the XML from a url in simplexml_load_file() function. Thank You for your help
My XML from URL:
<db>
<record>
<part>Part 1</part>
<qty>4</qty
</record>
<record>
<part>Part 2</part>
<qty>5</qty
</record>
<record>
<part>Part 1</part>
<qty>9</qty
</record>
</db>
Want to Display:
<db>
<record>
<part>Part 1</part>
<qty>13</qty>
</record>
<record>
<part>Part 2</part>
<qty>5</qty
</record>
</db>
Iterate over the XML document, accumulating part quantities as you go:
$simpleXmlElement = new SimpleXMLElement(<<<XML
<db>
<record>
<part>Part 1</part>
<qty>4</qty>
</record>
<record>
<part>Part 2</part>
<qty>5</qty>
</record>
<record>
<part>Part 1</part>
<qty>9</qty>
</record>
</db>
XML
);
$quantities = array();
foreach ($simpleXmlElement as $child) {
if ($child->part && $child->qty) {
$part = (string)$child->part;
if (!isset($quantities[$part])) {
$quantities[$part] = 0;
}
$quantities[$part] += (int)$child->qty;
}
}
echo json_encode($quantities);
simplexml_load_string() will parse the xml and build an array of all the records as 'record' => array(...)
you can then iterate the record array and group them by type
$parts = array();
foreach ($document['record'] as $item) {
if (isset($parts[$item['part']]) $parts[$item['part']] += $item['qty'];
else $parts[$item['part']] = $item['qty'];
}
after the above loop, $parts will contain a hash mapping the part name to qty