I'm creating an ecommerce site that has products with multiple attributes (size, colour, etc,.) so each attribute also has a number of values (for size these would be: small, medium, large, etc,.)
I have an array of id's representing the attributes like so:
$attributes = [1,2,3];
I then want to query my database for each of those id's to get th values for that attribute and create a multi-dimensional array of the results, like this:
array (size=3)
1 => size
0 => 'small'
1 => 'medium'
2 => 'large'
2 => colour
0 => 'red'
1 => 'green'
2 => 'blue'
3 => pattern
0 => 'spots'
1 => 'stripes'
2 => 'plain'
What I have so far is like this:
$attribute_array = [];
foreach($attributes as $attribute_id){
$params = [$attribute_id];
$sql = "SELECT * FROM attributes WHERE attribute_id=?";
$stmt = DB::run($sql,$params);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$attribute_value = $row['attribute_value'];
//$attribute_array[$attribute_id] = $attribute_value; // this only takes the last value from the last row
//array_push($attribute_array[$attribute_id],$attribute_value); // this says that the first arg isn't an array
}
}
What I want to achieve in the end is to get every combination of attributes for a product (small+red+stripes, small+green+stripes, small+blue+stripes, etc,.)
$attribute_array[$attribute_id] = $row;does the same as$attribute_array[$attribute_id] = $attribute_value;as in adding only the last row, but adds the additional id column as well