将多维 php 数组重组为另一个多维数组,其中第一个元素可以用作数组键

Reorganizing multidimentional php array to another multidimentional array where first elemnt can be used as array key

将以下数组转换为输出如下所示的最佳方式是什么。

初始数组

array:2 [▼
  0 => array:4 [▼
    "group" => "1"
    4 => "19"
    6 => "27"
    8 => "160"
  ]
  1 => array:4 [▼
    "group" => "2"
    4 => "20"
    6 => "28"
    8 => "200"
  ]
]

所需数组:

array:6 [▼
  0 => array:3 [▼
       "group" => "1"
       "es_variation_set_id" => "4" << this is key form the initial array
       "es_variation_id" => "19" << this is value form the initial array
 ]
  1 => array:3 [▼
       "group" => "1"
       "es_variation_set_id" => "6" << this is key form the initial array
       "es_variation_id" => "28" << this is value form the initial array
 ]
  2 => array:3 [▼
       "group" => "1"
       "es_variation_set_id" => "8" << this is key form the initial array
       "es_variation_id" => "160" << this is value form the initial array
 ]
  3 => array:3 [▼
       "group" => "2"
       "es_variation_set_id" => "4" << this is key form the initial array
       "es_variation_id" => "20" << this is value form the initial array
 ]
  4 => array:3 [▼
       "group" => "2"
       "es_variation_set_id" => "6" << this is key form the initial array
       "es_variation_id" => "28" << this is value form the initial array
 ]
  5 => array:3 [▼
       "group" => "1"
       "es_variation_set_id" => "8" << this is key form the initial array
       "es_variation_id" => "200" << this is value form the initial array
 ]       
]

这是我的foreach

    foreach ($request->only('product_variations')['product_variations'] as $variation_value)
    {

        if($variation_value['group'] != 0){
            dd($variation_value);
        }
    }

请提出解决此问题的最佳方法

提前致谢

您可以使用嵌套的 foreach 循环解决此问题,该循环每次都在 运行 之前提取 group 值。

$output = [];
foreach ($input as $subArray) {
    $group = $subArray['group'];
    unset($subArray['group']);
    foreach ($subArray as $setId => $variationId) {
        $output[] = [
            'group' => $group,
            'es_variation_set_id' => $setId,
            'es_variation_id' => $variationId,
        ];
    }
}

此处演示:https://3v4l.org/KLf8Y

你快到了。你只需要在if条件中再添加一个foreach来单独添加组,键值对。

<?php

$res = [];

foreach ($request->only('product_variations')['product_variations'] as $variation_value){
    if($variation_value['group'] != 0){
        foreach($variation_value as $k => $v){
            if($k == 'group') continue;
            $res[] = [
                'group' => $variation_value['group'],
                'es_variation_set_id' => $k,
                'es_variation_id' => $v
            ];
        }
    }
}

print_r($res);