3

次のような連想配列のインデックス付き配列があります。

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

brandおよびに基づいてグループ化するために、データを削減/マージ/再構築する必要がありmodelます。これら 2 つの列をグループ化する際にbrand&のmodel組み合わせが複数回発生する場合、size値はインデックス付きサブ配列に形成される必要があります。それ以外の場合、size値は単一の文字列値のままになる可能性があります。

私の望む結果:

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

4 に答える 4

3

アルゴリズムに関しては、次のことを行う必要があります。

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

ちなみに、アクセスしやすいように、サイズのサブ配列は常に配列になるようにしています。(つまり、要素になる可能性があることを許可する必要はありません。)

于 2010-08-12T15:05:59.033 に答える
0
//$array is the array in your first example.

foreach($array as $item) {
  $itemname = $item["brand"] . "_" . $item["model"]

  $new_array[$itemname]["brand"]  = $item["brand"];
  $new_array[$itemname]["model"]  = $item["model"];
  $new_array[$itemname]["size"][] = $item["size"];
}
于 2010-08-12T15:12:15.147 に答える
0

Knarf のスニペットへの「アップグレード」....

foreach($array as $item) {
  $itemname = $item["brand"] . "_" . $item["model"]

  $new_array[$itemname]["brand"]  = $item["brand"];
  $new_array[$itemname]["model"]  = $item["model"];
  $new_array[$itemname]["size"][ $item["size"] ] = 1;
}

foreach($new_array as $itemname=>$data) {
  if(isset($data['size']) && is_array($data['size'])) {
    $new_array[$itemname]['size']=array_keys($new_array[$itemname]['size']);
  }
}

もう重複はありません...

于 2010-08-12T15:33:50.460 に答える