使用另一个数组创建新的唯一阵列



我的项目中有一个简单的产品系统。我需要让我的产品选项名称和产品选项看起来像这样。"颜色" =>"红色,蓝色,黄色"大小" =>" S,M,L,XL"

我在数据库中的记录看起来像

Option names  Options    
Color,Size    Red-S        
Color,Size    Blue-S        
Color,Size    Yellow-S       
Color,Size    Red-M        
Color,Size    Blue-M        
Color,Size    Yellow-M        
Color,Size    Red-L

这是我的代码:

   foreach ($data as $product) {
       $variations = Products::where('group', $product['sku'])->get();
   }
       $count = count($variations);
       if($count > 0){
           $array2 = [];
           $ss = [];
           foreach($variations as $variants){
               $oname = explode(',', $variants['o_name']);
               $option = explode('-', $variants['option']);
               $array = array_combine($oname, $option);
               $array2[] = compact('array');
               $x = count($oname);
               $xz = $x - 1;
               for($i = 0; $i <= $xz; $i++){
                   $xs = $option[$i];
               }
               $ss[] = $xs;
           }
           dd($ss);

输出:

      array:12 [▼
      0 => "S"
      1 => "S"
      2 => "S"
      3 => "M"
      4 => "M"
      5 => "M"
      6 => "L"
      7 => "L"
      8 => "L"
      9 => "XL"
      10 => "XL"
      11 => "XL"
       ]

如何创建像这样的数组

"Color" => "Red,Blue,Yellow"
$variations = Products::where('group', $product['sku'])->get();
//This is me emulating your results
$variations = [];
$variations[]= ['o_name'=>'Color,Size', 'option' =>'Red-S'];
$variations[]= ['o_name'=>'Color,Size', 'option' =>'Blue-S'];
$variations[]= ['o_name'=>'Color,Size', 'option' =>'Yellow-S'];
$variations[]= ['o_name'=>'Color,Size', 'option' =>'Red-M'];
$variations[]= ['o_name'=>'Color,Size', 'option' =>'Blue-M'];
$variations[]= ['o_name'=>'Color,Size', 'option' =>'Yellow-M'];
$variations[]= ['o_name'=>'Color,Size', 'option' =>'Red-L'];
//get all the possible options here
$all_options = [];
foreach ( $variations as $variants) {
    $oname = explode(',', $variants['o_name']);
    $option = explode('-', $variants['option']);
    $all_options[] = array_combine($oname, $option);
}
//aggregating attributes and values
$unique = [];
$keys = array_keys( $all_options[0]);
foreach ($keys as $key) {
    $unique[$key] = array_map(function($option) use ($key){
        return $option[$key];
    },$all_options);
}
//selecting unique values
foreach ($unique as $key => $value) {
    $unique[$key] = array_unique($unique[$key]);
    $unique[$key] = implode(',',$unique[$key]);
}
var_dump($unique);

最新更新