使用 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中文网其他相关文章!