使用PHP 將數組行分組並形成子數組
按特定列值對多維數組中的行進行分組是一項常見任務在資料操作中。雖然沒有內建的 PHP 函數可以直接實現此目的,但自訂循環可以根據所選列有效地對行進行分組。
考慮以下多維數組:
$array = [ [ 'id' => 96, 'shipping_no' => '212755-1', 'part_no' => 'reterty', 'description' => 'tyrfyt', 'packaging_type' => 'PC', ], [ 'id' => 96, 'shipping_no' => '212755-1', 'part_no' => 'dftgtryh', 'description' => 'dfhgfyh', 'packaging_type' => 'PC', ], [ 'id' => 97, 'shipping_no' => '212755-2', 'part_no' => 'ZeoDark', 'description' => 's%c%s%c%s', 'packaging_type' => 'PC', ], ];
到按「id」列對數組進行分組,可以使用簡單的foreach 循環:
$result = []; foreach ($array as $element) { $result[$element['id']][] = $element; }
此循環迭代原始中的每個元素數組並將其儲存在“結果”數組中,其中“id”值作為鍵。結果,「結果」陣列將以「id」列分組:
Array ( [96] => Array ( [0] => Array ( [id] => 96 [shipping_no] => 212755-1 [part_no] => reterty [description] => tyrfyt [packaging_type] => PC ) [1] => Array ( [id] => 96 [shipping_no] => 212755-1 [part_no] => dftgtryh [description] => dfhgfyh [packaging_type] => PC ) ) [97] => Array ( [0] => Array ( [id] => 97 [shipping_no] => 212755-2 [part_no] => ZeoDark [description] => s%c%s%c%s [packaging_type] => PC ) ) )
以上是如何在 PHP 中按列值將多維數組行分組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!