繁体   English   中英

在 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;
        }
    }

这样做将返回一个属性数组并存储在 0 索引关联数组中。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM