基于两列对多维数组中的数据进行分组

2024-03-07

我有一个关联数组的索引数组,如下所示:

[
    ['brand' => 'ABC', 'model' => 'xyz', 'size' => 13],
    ['brand' => 'QWE', 'model' => 'poi', 'size' => 23],
    ['brand' => 'ABC', 'model' => 'xyz', 'size' => 18]
];

我需要减少/合并/重组数据以基于brand and model。如果在对这两列进行分组时,brand & model组合出现多次,则size值应该形成一个索引子数组。否则,size值可以保留为单个字符串值。

我想要的结果:

[
    ['brand' => 'ABC', 'model' => 'xyz', 'size' => [13, 18]],
    ['brand' => 'QWE', 'model' => 'poi', 'size' => 23],
];

就算法而言,您只需要:

  1. 创建一个空数组。

  2. 扫描源数组中的每个数组元素,为遇到的每个新品牌/型号创建一个新元素(在空数组中)并添加尺寸子数组。

  3. 如果已经有品牌/型号条目,只需将尺寸添加到子数组中(如果尚不存在)。

您可以按如下方式实现(粗略,但它有效):

<?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);
?>

顺便说一句,为了便于访问,我将 size 子数组设置为始终是一个数组。 (即:您不必允许它可能只是一个元素。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

基于两列对多维数组中的数据进行分组 的相关文章

随机推荐