【发布时间】:2025-12-28 18:50:12
【问题描述】:
我正在创建一个电子商务网站,其中包含具有多个属性(尺寸、颜色等)的产品。因此每个属性也有许多值(对于尺寸,这些值是:小、中、大等。 )
我有一个表示属性的 id 数组,如下所示:
$attributes = [1,2,3];
然后我想在我的数据库中查询每个 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'
我目前的情况是这样的:
$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
}
}
我最终想要实现的是获得产品的每种属性组合(小+红色+条纹、小+绿色+条纹、小+蓝色+条纹等)。
【问题讨论】:
-
$attribute_array[] = $row ?
-
@Jesse 感谢您的评论,
$attribute_array[$attribute_id] = $row;与$attribute_array[$attribute_id] = $attribute_value;的作用相同,只添加了最后一行,但也添加了额外的 id 列
标签: php multidimensional-array associative-array