Reputation: 15
Apologies in advance since I'm a PHP novice and I'm sure I'm not using the right terms here.
I am making an automated product data feed using a set of provided SKUs, but the feed requires separate entries for size and gender variation of the products.
Is there a simple way to take this:
$SKUs = array('Product1', 'Product2', 'Product3')
And "multiply" each entry in the array with these:
$gender = array('M', 'F');
$size = array('S', 'M', 'L', 'XL');
So that I end up with this result:
$feed = array('Product1M-S', 'Product1M-M', 'Product1M-L', 'Product1M-XL', 'Product1F-S'...)
Upvotes: 1
Views: 294
Reputation: 2851
$feed = array();
foreach ($SKUs as $sku) {
foreach ($gender as $g) {
foreach ($size as $s) {
$feed[] = $sku.$g.'-'.$s;
}
}
}
print_r($feed);
Maybe there exists a simple array function, but this one is easy to read, and ready for future "easy" changes.
PS. This is a great lecture with a similar problem: http://dannyherran.com/2011/06/finding-unique-array-combinations-with-php-permutations/
PS2. As KA_lin suggested, you can make a function to do this, however, I haven't got knowledge about the array and product structure, and don't know if i.e. the sizes are always the same (S, L, X) for each product. If the arrays are always the same, they can be hardcoded inside the function body as KA_lin suggested. I presented only a linear solution, but You can easily upgrade it too Your needs.
Upvotes: 7
Reputation: 9432
You just have to iterate through all 3 arrays at once and append to a new array like this:
$SKUs = array('Product1', 'Product2', 'Product3')
function generate_product_combinations($SKUs)
{
$size = array('S', 'M', 'L', 'XL');//these 2 arrays are universal
$gender = array('M', 'F'); //and can belong here rather than params
$final = array(); //but should be taken from a config
foreach($SKUs as $sku)
{
foreach($size as $size_shirt)
{
foreach($gender as $sex)
{
$final[]=$sku.$gender.'-'.$sex;
}
}
}
return $final;
}
$products = generate_product_combinations($SKUs);
Upvotes: 2