分段迭代

时间:2018-02-24 22:38:01

标签: php

我正在使用PHP V7.1.9,而我正在做的是从MySQL表返回一些行,返回数据如下所示:

+-------------+-------+-------------+------------------+---------------------------+
| sequence_id | title | description | customer_type_id | customer_type_description |
+-------------+-------+-------------+------------------+---------------------------+
|      1      |  ...  |     ...     |        1         |          customer         |
|      2      |  ...  |     ...     |        1         |          customer         |
|      3      |  ...  |     ...     |        1         |          customer         |
|      4      |  ...  |     ...     |        2         |          prospect         |
|      5      |  ...  |     ...     |        3         |          winback          |
|      6      |  ...  |     ...     |        3         |          winback          |
|      7      |  ...  |     ...     |        4         |          business         |
+-------------+-------+-------------+------------------+---------------------------+

我需要做的是每个行的动态<option>元素,但是,我还想根据<optgroup>(或{customer_type_idcustomer_type_description元素中的每个选项进行细分{1}})。因此,创建的结果DOM看起来像这样:

<optgroup label="customer" data-customer-type-id="1">
  <option value="1" data-description="...">...</option>
  ...
</optgroup>
<optgroup label="prospect" data-customer-type-id="2">
  <option value="4" data-description="...">...</option>
</optgroup>
...

我怎样才能将For / Each迭代分段到我最初循环遍历每个customer_type_id的位置,并且在该循环内部有一个嵌套的For / Each循环来迭代遍历与外部循环的id匹配的每一行?

1 个答案:

答案 0 :(得分:1)

您必须存储一个维护最后一个ID的本地变量。然后,检查最后一个是否与当前不同:

// I used a "computed variable", to overcome the compiler errors, 
// we need a helper variable to store the actual value.
var globalVariable_Value : Int = 0

// this is the global "variable" we worked with
var globalVariable : Int {

    // the setter
    set (newValue) {
        globalDataQueue.async(flags: .barrier) {
            globalVariable_Value = newValue
        }
    }

    // the getter
    get {
        // we need a helper variable to store the result.
        // inside a void closure you are not allow to "return"
        var result : Int = 0
        globalDataQueue.sync{
            result = globalVariable_Value
        }
        return result
    }
}

// usage
globalVariable = 1
print ("globalVariable == \(globalVariable)")

globalVariable += 1
print ("globalVariable == \(globalVariable)")

// output
// globalVariable == 1
// globalVariable == 2

输出:

$last_customer_type_id = 0 ;
if (!empty($array)) {
    foreach ($array as $item) {
        if ($last_customer_type_id != $item['customer_type_id']) {
            if ($last_customer_type_id != 0) {
                echo '</optgroup>' ;
            }
            $last_customer_type_id = $item['customer_type_id'] ;
            echo '<optgroup label="customer" data-customer-type-id="'.$item['customer_type_id'].'">' ;
        }
        echo '   <option value="'.$item['sequence_id'].'" data-description="...">...</option>' ;
    }
    echo '</optgroup>' ;
}