Check for array value change during foreach loop php

2k Views Asked by At

I'm exporting from MySQL into an Excel spreadsheet, the export works fine however I'm trying to change how the output works from the array.

Example of the array

Array
(
[0] => Array
    (
        [Product] => ABYT8
        [Invoice Date] => 24/04/2018
        [Carriage] => 31.00
        [Carriage Tax Code] => T0
        [Order Number] => 223
    )

[1] => Array
    (
        [Product] => CASTSRF
        [Invoice Date] => 24/04/2018
        [Carriage] => 0.00
        [Carriage Tax Code] => T1
        [Order Number] => 224
    )

[2] => Array
    (
        [Product] => 12K816
        [Invoice Date] => 24/04/2018
        [Carriage] => 0.00
        [Carriage Tax Code] => T1
        [Order Number] => 224
    )
)

Array 0 is for Sale 223 and Array 1 & 2 are for Sale 224.

The foreach that loops through this array and outputs to Excel is as follows:

foreach ($export_array as $row) {
    if (!$flag) {
      // display field/column names as first row
        echo implode("\t", array_keys($row)) . "\n";
        $flag = true;
    }       
    array_walk($row, __NAMESPACE__ . '\cleanData');
    echo implode("\t", array_values($row)) . "\n";
}

I only want to output the Carriage & Carriage Tax Code values on the first iteration for each Sales Order Number but I don't know how to do this. I tried re writing the entire thing which grouped the data into a multidimensional array that was grouped by Order Number, which worked but then I failed in getting the export to work.

1

There are 1 best solutions below

1
Don't Panic On

General pattern for keeping track of changing groups as you iterate an array:

// keep track of the previous value of the group column as you iterate
$previousOrderNumber = null;

foreach ($export_array as $index => $row) {
    if ($row['Order Number'] != $previousOrderNumber) {
        // it's a new order number, so print the Carriage stuff
    } else {
        // it's the same order number, so don't
    }

    // current becomes previous
    $previousOrderNumber = $row['Order Number'];
}

This does depend on the array being sorted by the group column (Order Number in this case), so be sure that's done in your query, or usort the array if it doesn't come from a database.