用另一个数组创建新的唯一数组

时间:2019-05-07 13:05:47

标签: php arrays laravel

我的项目中有一个简单的产品系统。我需要获取我的产品选项名称,并且产品选项如下所示。 “颜色” =>“红色,蓝色,黄色” “ Size” =>“ 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"

2 个答案:

答案 0 :(得分:0)

我不确定我是否了解内部for循环,但是您可以那样做-将{值保存为$ss(根据每个选项名称)作为键值,然后在循环提取amd后爆破他们。

array_combine之后执行:

foreach($array as $name => $v) {
    $ss[$name][$v] = true;
}

在所有循环之后,仅获取关键点并内爆:

foreach($ss as &$arr) {
    $arr = implode(",", array_keys($arr));
}

这是使事情变得更简单的实时示例:3v4l

答案 1 :(得分:0)

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