Php 使用foreach将数组添加到数组项
我正在为我的产品变体制作最后一个大阵列,我有一个尺寸和颜色阵列。如何使用foreach将每个元素的大小和颜色数组添加到products数组中Php 使用foreach将数组添加到数组项,php,Php,我正在为我的产品变体制作最后一个大阵列,我有一个尺寸和颜色阵列。如何使用foreach将每个元素的大小和颜色数组添加到products数组中 $sizes = [ [ 'property_id' => $property_size, 'property_name' => 'Style', 'values' => ['S
$sizes = [
[
'property_id' => $property_size,
'property_name' => 'Style',
'values' => ['Small'],
],
[
'property_id' => $property_size,
'property_name' => 'Style',
'values' => ['Large'],
],
];
$colors = [
[
'property_id' => $property_fastener,
'property_name' => 'Color',
'values' => ['Red'],
],
[
'property_id' => $property_fastener,
'property_name' => 'Color',
'values' => ['Blue'],
],
];
$products = [
[
'property_values' => [$sizes[0], $colors[0]],
'sku' => $product['sku'],
'offerings' => [
[
'price' => $price,
'quantity' => $quantity,
'is_enabled' => 1
]
]
],
[
'property_values' => [$sizes[0], $colors[1]],
'sku' => $product['sku'],
'offerings' => [
[
'price' => $price,
'quantity' => $quantity,
'is_enabled' => 1
]
]
],
[
'property_values' => [$sizes[1], $colors[0]],
'sku' => $product['sku'],
'offerings' => [
[
'price' => $price,
'quantity' => $quantity,
'is_enabled' => 1
]
]
],
[
'property_values' => [$sizes[1], $colors[1]],
'sku' => $product['sku'],
'offerings' => [
[
'price' => $price,
'quantity' => $quantity,
'is_enabled' => 1
]
]
],
];
正如你们所看到的,我自己制作了$products数组,但我会添加10种不同的颜色和10种不同的大小,所以不可能这样制作。如何使用foreach创建此阵列?好的,我已设法做到了。这很容易达到我的预期,以下是代码:
$sizes = [
[
'property_id' => $property_size,
'property_name' => 'Style',
'values' => ['Small'],
],
[
'property_id' => $property_size,
'property_name' => 'Style',
'values' => ['Large'],
],
];
$colors = [
[
'property_id' => $property_fastener,
'property_name' => 'Color',
'values' => ['Red'],
],
[
'property_id' => $property_fastener,
'property_name' => 'Color',
'values' => ['Blue'],
],
];
$products = [
[
'property_values' => [$sizes[0], $colors[0]],
'sku' => $product['sku'],
'offerings' => [
[
'price' => $price,
'quantity' => $quantity,
'is_enabled' => 1
]
]
],
[
'property_values' => [$sizes[0], $colors[1]],
'sku' => $product['sku'],
'offerings' => [
[
'price' => $price,
'quantity' => $quantity,
'is_enabled' => 1
]
]
],
[
'property_values' => [$sizes[1], $colors[0]],
'sku' => $product['sku'],
'offerings' => [
[
'price' => $price,
'quantity' => $quantity,
'is_enabled' => 1
]
]
],
[
'property_values' => [$sizes[1], $colors[1]],
'sku' => $product['sku'],
'offerings' => [
[
'price' => $price,
'quantity' => $quantity,
'is_enabled' => 1
]
]
],
];
$i = 0;
foreach ($sizes as $sv)
{
foreach ($colors as $cv)
{
$products[$i]['property_values'] = [$sv, $cv];
$products[$i]['sku'] = $product['sku'];
$products[$i]['offerings'][0] = array('price' => $price,'quantity' => $quantity, 'is_enabled' => 1);
$i++;
}
}