问题
I have this array of attributes for example:
Array
(
[0] => Array
(
[id] => 20
[title] => Brown
[parent_id] => 1
[parent_title] => Color
[isMultiple] => 1
)
[1] => Array
(
[id] => 21
[title] => Cream
[parent_id] => 1
[parent_title] => Color
[isMultiple] => 1
)
[2] => Array
(
[id] => 61
[title] => S
[parent_id] => 2
[parent_title] => Size
[isMultiple] => 1
)
[3] => Array
(
[id] => 62
[title] => M
[parent_id] => 2
[parent_title] => Size
[isMultiple] => 1
)
[4] => Array
(
[id] => 63
[title] => L
[parent_id] => 2
[parent_title] => Size
[isMultiple] => 1
)
)
from this array we can understand that we have 6 variations of inventory:
1 | Brown | S
2 | Brown | M
3 | Brown | L
4 | Cream | S
5 | Cream | M
6 | Cream | L
What is the correct way to loop over this array to create another array of the 6 variations like in the above example.
let's assume that I have another 2 attrs in the array like this:
[5] => Array ( [id] => 64 [title] => Cotton [parent_id] => 3 [parent_title] => Metiral [isMultiple] => 1 ) [6] => Array ( [id] => 65 [title] => Wool [parent_id] => 3 [parent_title] => Metiral [isMultiple] => 1 )
How I can loop on this array to create variations like these:
1 | Brown | S | wool
2 | Brown | S | cotton
3 | Brown | M | wool
4 | Brown | M | cotton
5 | Brown | L | wool
6 | Brown | L | cotton
7 | Cream | S | wool
8 | Cream | S | cotton
9 | Cream | M | wool
10 | Cream| M | cotton
11 | Cream| L | wool
12 | Cream| L | cotton
Thanks in advance!
回答1:
OK I found the solution:
A. right, I made an associative arrays of all my attributes:
Array (
[0] => Array
(
[0] => 20
[1] => 21
)
[1] => Array
(
[0] => 61
[1] => 62
[2] => 63
)
)
B. then I recursively create the whole possible variations:
function buildVariants($arrays, $i = 0) {
if (!isset($arrays[$i])) {
return array();
}
if ($i == count($arrays) - 1) {
return $arrays[$i];
}
// get combinations from subsequent arrays
$tmp = $this->buildVariants($arrays, $i + 1);
$result = array();
// concat each array from tmp with each element from $arrays[$i]
foreach ($arrays[$i] as $v) {
foreach ($tmp as $t) {
$result[] = is_array($t) ? array_merge(array($v), $t) : array($v, $t);
}
}
return $result;
}
C. then I add it to tables in this structure:
See tables stru
回答2:
Maybe start with "cleaning" your data first:
$attr = array();
foreach( $attributes as $attribute ){
$attr[$attribute['parent_title']][] = $attribute['title'];
}
So that you have something like
array(
"Color" => array(
"Color1",
"Color2",
"Color3"
),
"Size" => array(
"Size1",
"Size2",
"Size3"
),
//...
);
From there on this should be helpful:
How to generate in PHP all combinations of items in multiple arrays
来源:https://stackoverflow.com/questions/20835464/loop-on-attributes-to-create-inventory-variations