PHP: Help with Loop - Grouping Like Records within Array

Status
Not open for further replies.

geoffm33

Ars Scholae Palatinae
710
I am writing a PHP script that will convert a CSV file into an XML file for use with our order management software.

Here is an example of the CSV file for the order being placed:

Code:
Order#	SKU	QTY	BuyerName
1234	REDWIDGET2	2	Geoff
1239	REDWIDGET2	3	Bill
1578	BLUEWIDGET1	5	Gary
1578	REDWIDGET2	5	Gary

As you can see, If there are multiple products ordered within the same purchase order #, it is represented on multiple lines in the CSV file (order 1578 in example above).

The XML I am outputting has an order envelope that contains the order level info, and then each product ordered in it's own section, example:

Code:
<Order>
	<OrderNumber>1578</OrderNumber>
	<BuyerName>Gary</BuyerName>
	<Products>
		<Product>
			<SKU>BLUEWIDGET1</SKU>
			<Quantity>5</Quantity>
		</Product>
		<Product>
			<SKU>REDWIDGET2</SKU>
			<Quantity>5</Quantity>
		</Product>
	</Products>
</Order>

I am calling the CSV file into an array, looping through and creating an Order section for each line. So essentially I am creating two orders for Gary's order #1578 instead of one order with two product sections.

How can I create a loop at the Products section to iterate through any records in the CSV file with the same order number?

Thanks for any help!
 

Schluppy

Ars Tribunus Militum
2,486
It depends upon how you're creating the XML. You should post your code.

Two ways come to mind. The first involves a multidimensional array using the order numbers as indices. As you loop through the CSV, you simply add more products the $orders[$orderId]['Products'] array and maybe end up with something like the following, to be converted later to XML in one shot.

Code:
Array // $orders
(
    [1234] => Array
        (
            [BuyerName] => Geoff
            [Products] => Array
                (
                    [REDWIDGET2] => 2
                )

        )

    [1239] => Array
        (
            [BuyerName] => Bill
            [Products] => Array
                (
                    [REDWIDGET2] => 3
                )

        )

    [1578] => Array
        (
            [BuyerName] => Gary
            [Products] => Array
                (
                    [BLUEWIDGET1] => 5
                    [REDWIDGET2] => 5
                )

        )

)

If you're using DomDocument or something and creating the XML nodes as you loop through the CSV, just keep an additional array of order numbers, check to see if the current order number already exists in the array, and if it does find the corresponding 'Products' node in your DomDocument and insert a new 'Product' node.
 
Status
Not open for further replies.