[英]Creating a multidimensional array from database query in PHP
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:我有一组 id 表示属性,如下所示:
$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:然后我想为每个 id 查询我的数据库以获取该属性的值并创建结果的多维数组,如下所示:
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,.)我最终想要实现的是获得产品的所有属性组合(小+红色+条纹、小+绿色+条纹、小+蓝色+条纹等)。
You were almost there...你快到了...
$attribute_array[$attribute_id][] = $attribute_value;
note the []
which adds the value to the list of values already there - without it it will just overwrite the previous value.注意[]
将值添加到已经存在的值列表中 - 如果没有它,它只会覆盖以前的值。
$attribute_array = [];
foreach($attributes as $attribute_id){
$params = [$attribute_id];
$sql = "SELECT size,colour,pattern,etc FROM attributes WHERE attribute_id=?";
$stmt = DB::run($sql,$params);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
// $attribute_value = $row['attribute_value'];
$attribute_array[] = $row;
}
}
Doing this way will return an array of the attributes and store in 0-indexed associative array.这样做将返回一个属性数组并存储在 0 索引关联数组中。
$attribute_array[0][size,colour,pattern]
Example: $size = $attribute_array[0]['size']示例:$size = $attribute_array[0]['size']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.