我會personnaly去這樣的事情:創建一個新的有序排列,其中每個父元素包含了他所有的孩子在一個子陣列
<?php
$data =
[
['iditemCat' => 1, 'itemCatName' => 'Admin', 'itemCatChildof' => 0],
['iditemCat' => 2, 'itemCatName' => 'Admin2', 'itemCatChildof' => 1],
['iditemCat' => 3, 'itemCatName' => 'Admin3', 'itemCatChildof' => 1],
['iditemCat' => 4, 'itemCatName' => 'Admin4', 'itemCatChildof' => 1],
['iditemCat' => 5, 'itemCatName' => 'Admin5', 'itemCatChildof' => 0],
['iditemCat' => 6, 'itemCatName' => 'Admin6', 'itemCatChildof' => 5],
['iditemCat' => 7, 'itemCatName' => 'Admin7', 'itemCatChildof' => 5],
['iditemCat' => 8, 'itemCatName' => 'Admin8', 'itemCatChildof' => 5]
];
$sortedArray = [];
foreach($data as $d) {
if($d['itemCatChildof'] == 0) {
$sortedArray[$d['iditemCat']] = $d;
} else {
$sortedArray[$d['itemCatChildof']]['children'][] = $d;
}
}
它會返回你是這樣的:
Array
(
[1] => Array
(
[iditemCat] => 1
[itemCatName] => Admin
[itemCatChildof] => 0
[children] => Array
(
[0] => Array
(
[iditemCat] => 2
[itemCatName] => Admin2
[itemCatChildof] => 1
)
[1] => Array
(
[iditemCat] => 3
[itemCatName] => Admin3
[itemCatChildof] => 1
)
[2] => Array
(
[iditemCat] => 4
[itemCatName] => Admin4
[itemCatChildof] => 1
)
)
)
[5] => Array
(
[iditemCat] => 5
[itemCatName] => Admin5
[itemCatChildof] => 0
[children] => Array
(
[0] => Array
(
[iditemCat] => 6
[itemCatName] => Admin6
[itemCatChildof] => 5
)
[1] => Array
(
[iditemCat] => 7
[itemCatName] => Admin7
[itemCatChildof] => 5
)
[2] => Array
(
[iditemCat] => 8
[itemCatName] => Admin8
[itemCatChildof] => 5
)
)
)
)
所以你就必須去探索它是這樣的:
<select name="foo" id="foo">
<?php foreach($sortedArray as $value): ?>
<optgroup label="<?= $value['itemCatName']; ?>">
<?php foreach($value['children'] as $child): ?>
<option value="<?= $child['iditemCat']; ?>"><?= $child['itemCatName']; ?></option>
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
</select>