合并和分组数组数据

编程入门 行业动态 更新时间:2024-10-25 10:24:49
本文介绍了合并和分组数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何对此分组:

Array( [0] => Array( [brand] => 'ABC', [model] => 'xyz', [size] => 13 ) [1] => Array( [brand] => 'QWE', [model] => 'poi', [size] => 23 ) [2] => Array( [brand] => 'ABC', [model] => 'xyz', [size] => 18 ) )

到此:

Array( [0] => Array( [brand] => 'ABC', [model] => 'xyz', [size] => Array( 13, 18 ) ) [1] => Array( [brand] => 'QWE', [model] => 'poi', [size] => 23 ) )

我想按BRAND和MODEL分组,但要在其中插入一个数组大小,因为这是不一样的。

I want to group by BRAND and MODEL, but insert an array in the SIZE, since this one is not the same.

推荐答案

就算法而言,您只需要:

In terms of the algorithm, you simply need to:

  • 创建一个空数组。

  • Create an empty array.

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

    Scan each array element in the source array creating a new element (in the empty array) for each new brand/model encountered and adding the size sub-array.

    如果已经有一个品牌/型号条目,只需将大小添加到子数组(如果尚不存在)。

    If there's already a brand/model entry, simply add the size to the sub-array if it's not already present.

    您可以实现如下所示(粗略,但可行):

    You could implement this as follows (crude, but it works):

    <?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子数组始终是数组。 (即:您不必让它可能只是一个元素。)

    Incidentally, for ease of access I've made it so that the size sub-array is always an array. (i.e.: You don't have to allow for it to potentially only be an element.)

  • 更多推荐

    合并和分组数组数据

    本文发布于:2023-10-17 10:24:51,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1500639.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:数组   数据

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!