How Can I combine a list from XML in PHP -
i have parts list coming xml file, goes below. want able generate using php combined list. example "part 1" recorded twice. want qty show 13 under part 1 when generated either in json output or xml output. best way of doing that? looked @ php function array_combine wasn't able figure out if values combined mathematically instead of showing 1 of results. loading xml url in simplexml_load_file() function. thank help
my xml 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 display:
<db> <record> <part>part 1</part> <qty>13</qty> </record> <record> <part>part 2</part> <qty>5</qty </record> </db>
iterate on xml document, accumulating part quantities 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 $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);
Comments
Post a Comment