I have this situation :
$variation = [
"sku" => [
0 => "dSADad",
1 => "ASDAF",
2 => "ASFAS",
// ...
],
"Price" => [
0 => "1",
1 => "1",
2 => "1",
// ...
],
"Quantity" => [
0 => "123",
1 => "123",
2 => "123434",
// ...
],
"attributes" => [
"Color" => [
0 => "5",
1 => "4",
2 => "4",
// ...
],
"Size" => [
0 => "3",
1 => "3",
2 => "2",
// ...
],
"Material" => [
0 => "7",
1 => "7",
2 => "8",
// ...
],
],
];
And I want to transform it to be grouped by separate variants, as in the example below:I tried several options but without result. I also tried with JS to add an index to the input before submitting, but it still doesn't work. The only option left is to transform it into php..
$variations = [
0 => [
"Sku" => [
0 => "dSADad",
],
"Price" => [
0 => "1",
],
"Quantity" => [
0 => "123",
],
"attributes" => [
"Color" => [
0 => "5",
],
"Size" => [
0 => "3",
],
"Material" => [
0 => "7",
],
],
],
1 => [
"Sku" => [
1 => "ASDAF",
],
"Price" => [
1 => "1",
],
"Quantity" => [
1 => "123",
],
"attributes" => [
"Color" => [
1 => "4",
],
"Size" => [
1 => "3",
],
"Material" => [
1 => "7",
],
// ....
],
]
// ...
];
CodePudding user response:
I managed to make this piece of code:
function extractVariation($variations, $key)
{
$variation = [];
foreach ($variations as $property => $values) {
if (isset($values[$key])) {
$variation[$property] = $values[$key];
} else {
$variation[$property] = extractVariation($values, $key);
}
}
return $variation;
}
$newVariations = [];
foreach ($variations['sku'] as $key => $sku) {
$newVariations[] = extractVariation($variations, $key);
}
var_export($newVariations);
See a working example here: https://3v4l.org/l4gJQ
Note that I renamed your $variation
array into $variations
.
The function is recursive, which allows it to go into the attributes array.
The output is:
array (
0 =>
array (
'sku' => 'dSADad',
'Price' => '1',
'Quantity' => '123',
'attributes' =>
array (
'Color' => '5',
'Size' => '3',
'Material' => '7',
),
),
1 =>
array (
'sku' => 'ASDAF',
'Price' => '1',
'Quantity' => '123',
'attributes' =>
array (
'Color' => '4',
'Size' => '3',
'Material' => '7',
),
),
2 =>
array (
'sku' => 'ASFAS',
'Price' => '1',
'Quantity' => '123434',
'attributes' =>
array (
'Color' => '4',
'Size' => '2',
'Material' => '8',
),
),
)
It is always better to show what you've tried, even if it doesn't work completely. That way people here can see that you're not simply asking them to write code for you, but that you really have a problem.