我有一个这样的关联数组的索引数组:
[
['brand' => 'ABC', 'model' => 'xyz', 'size' => 13],
['brand' => 'QWE', 'model' => 'poi', 'size' => 23],
['brand' => 'ABC', 'model' => 'xyz', 'size' => 18]
];
我需要减少/合并/重组数据以根据brand
和model
进行分组。如果在对这两列进行分组时,brand
和 model
组合出现不止一次,则 size
值应形成一个索引子数组。否则,size
值可以保留为单个字符串值。
我想要的结果:
[
['brand' => 'ABC', 'model' => 'xyz', 'size' => [13, 18]],
['brand' => 'QWE', 'model' => 'poi', 'size' => 23],
];
最佳答案
在算法方面,您只需要:
创建一个空数组。
扫描源数组中的每个数组元素,为遇到的每个新品牌/型号创建一个新元素(在空数组中)并添加尺寸子数组。
如果已有品牌/型号条目,则只需将其大小添加到子数组(如果尚不存在)。
您可以按如下方式实现(粗略但有效):
<?php
// Test data.
$sourceArray = array(array('brand'=>'ABC', 'model'=>'xyz', 'size'=>13),
array('brand'=>'QWE', 'model'=>'poi', 'size'=>23),
array('brand'=>'ABC', 'model'=>'xyz', 'size'=>18),
);
$newArray = array();
// Create a new array from the source array.
// We'll use the brand/model as a lookup.
foreach($sourceArray as $element) {
$elementKey = $element['brand'] . '_' . $element['model'];
// Does this brand/model combo already exist?
if(!isset($newArray[$elementKey])) {
// No - create the new element.
$newArray[$elementKey] = array('brand'=>$element['brand'],
'model'=>$element['model'],
'size'=>array($element['size']),
);
}
else {
// Yes - add the size (if it's not already present).
if(!in_array($element['size'], $newArray[$elementKey]['size'])) {
$newArray[$elementKey]['size'][] = $element['size'];
}
}
}
// *** DEBUG ***
print_r($newArray);
?>
顺便说一下,为了便于访问,我已经做到了大小子数组始终是一个数组。 (即:您不必允许它可能只是一个元素。)
关于php - 基于两列对多维数组中的数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3469078/