1

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'...)
2
  • 3
    Have you tried anything? Commented Jul 25, 2014 at 6:57
  • yes @wumm, I primarily tried various array functions like array_combine and array_merge, but those obviously didn't suit my purposes. I did also try doing a foreach loop with my arrays, but it didn't work for me. Being new to PHP, I didn't know I needed the empty brackets to properly pass my variables. Commented Jul 26, 2014 at 20:02

2 Answers 2

7
$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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.