代码之家  ›  专栏  ›  技术社区  ›  Paddy Hallihan

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

  •  0
  • Paddy Hallihan  · 技术社区  · 7 年前

    我有一个id数组,表示如下属性:

    $attributes = [1,2,3];
    

    然后,我想在数据库中查询每个id,以获取该属性的th值,并创建结果的多维数组,如下所示:

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

    我最终想要实现的是获得产品的所有属性组合(小+红+条纹、小+绿+条纹、小+蓝+条纹等)

    2 回复  |  直到 5 年前
        1
  •  1
  •   Nigel Ren    7 年前

    $attribute_array[$attribute_id][] = $attribute_value;
    

    注意 [] 它将值添加到已经存在的值列表中-如果没有它,它将只覆盖以前的值。

        2
  •  0
  •   Jeffrey Meyer    7 年前
        $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\u数组[0]['size']