从 PHP 中的数据库查询创建多维数组

Creating a multidimensional array from database query in PHP

我正在创建一个电子商务网站,其中包含具有多个属性(大小、颜色等)的产品,因此每个属性也有多个值(对于大小,这些值将是:小、中、大等,.)

我有一个 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[$attribute_id][] = $attribute_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;
        }
    }

这样做会 return 属性数组并存储在 0 索引关联数组中。

    $attribute_array[0][size,colour,pattern]

示例: $大小 = $attribute_array[0]['size']