1

I've searched through all the posts here and can't seem to find the right method to do what I need.

I have a multi-dimensional array of products pulled from a db, via individual orders.

$products = array ();

$i = count ($products);

foreach ($orders as $order):
$res = mysql_query ("SELECT * FROM orders_products AS op LEFT JOIN orders_products_attributes AS opa ON op.orders_products_id = opa.orders_products_id WHERE op.orders_id = '$order'");
while ($row = mysql_fetch_array ($res)):
    $products[$i] = array (
        "model"     => $row['products_model'],
        "name"      => $row['products_name'],
        "option"    => $row['products_options_values'] ?  $row['products_options_values'] : "N/A",
        "qty"       => (int)$row['products_quantity']
    );
    $i++;
endwhile;
endforeach;

Some products have multiple options ie color or box size etc.

I need to create a new array which contains entries for each product according to option and updates the quantities where the option is the same from the existing products array.

This is what I'm trying but I can't seem to get it right.

$items = array ();

$j = count ($items);

foreach ($products as $product):
      $exists = searchSubArray ($items, "model", $product['model']);
      if ($exists and ($exists['option'] == $product['option'])):
        // no matter what I do here I get either all the products, or
        // products without new quantities
      else:
        $items[$j] = array (
        "model" => $product['model'],
        "name" => $product['name'],
        "option" => $product['option'],
        "qty" => $product['qty']
        );
      endif;
$j++;
endforeach;

And here is the searchSubArray function that I came across while searching here for an answer to this.

function searchSubArray (Array $array, $key, $value) {   
    foreach ($array as $subarray): 
        if (isset ($subarray[$key]) && $subarray[$key] == $value)
          return $subarray;       
    endforeach;
}

Any suggestion on how I might implement this?

Charles Sprayberry
  • 7,741
  • 3
  • 41
  • 50
secondman
  • 3,233
  • 6
  • 43
  • 66
  • Though it may seem off-topic, I'd suggest you to look at "Map and Reduce" algorithm (there are implementations for PHP as well). Can be easily googled. – Stan Feb 11 '12 at 21:09
  • "Some products have multiple options ie color or box size etc." - Why don't you create columns and tables for that? I smell bad designed database... – inf3rno Feb 15 '12 at 04:21
  • @inf3mo Yeah totally agreed, it's for a version of CRE Loaded, probably the worst shopping cart in history, I have no control over the design of the db, just trying to pull existing data to help the productivity of the team filling the orders. – secondman Feb 27 '12 at 07:34

0 Answers0