0

I'm creating an ecommerce site that has products with multiple attributes (size, colour, etc,.) so each attribute also has a number of values (for size these would be: small, medium, large, etc,.)

I have an array of id's representing the attributes like so:

$attributes = [1,2,3];

I then want to query my database for each of those id's to get th values for that attribute and create a multi-dimensional array of the results, like this:

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'

What I have so far is like this:

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

What I want to achieve in the end is to get every combination of attributes for a product (small+red+stripes, small+green+stripes, small+blue+stripes, etc,.)

2
  • $attribute_array[] = $row ? Commented Sep 21, 2018 at 16:08
  • @Jesse thanks for your comment, $attribute_array[$attribute_id] = $row; does the same as $attribute_array[$attribute_id] = $attribute_value; as in adding only the last row, but adds the additional id column as well Commented Sep 21, 2018 at 16:13

2 Answers 2

1

You were almost there...

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

note the [] which adds the value to the list of values already there - without it it will just overwrite the previous value.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you so much exactly what I was looking for. Will accept you answer a.s.a.p.
0
    $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;
        }
    }

Doing this way will return an array of the attributes and store in 0-indexed associative array.

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

Example: $size = $attribute_array[0]['size']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.