簡體   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