在foreach循环php中检查数组值的变化

时间:2018-04-24 15:30:18

标签: php arrays

我从MySQL导出到Excel电子表格,导出工作正常,但我正在尝试更改输出从数组中的工作方式。

数组示例

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
    )
)

阵列0用于销售223和阵列1& 2是出售224。

循环遍历此数组并输出到Excel的foreach如下:

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";
  }

我只想输出Carriage&每个销售订单号的第一次迭代中的运输税代码值,但我不知道如何执行此操作。我尝试重新编写将数据分组为多维数组的整个事物,该数组按订单号分组,但有效但后来我无法使导出工作。

任何指针都会非常感激

1 个答案:

答案 0 :(得分:0)

在迭代数组时跟踪更改组的一般模式:

// 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'];
}

这取决于按组列排序的数组(在本例中为Order Number),因此请确保在查询中完成,或者如果数组不是来自数据库,则使用数组。