搜索和更新多维数组

时间:2012-02-06 13:23:58

标签: php search multidimensional-array updating

我在这里搜索了所有帖子,似乎找不到合适的方法来做我需要的。

我通过个人订单从数据库中提取了多维数据。

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

有些产品有多种选择,即颜色或盒子大小等。

我需要根据选项创建一个新数组,其中包含每个产品的条目,并更新现有产品数组中选项相同的数量。

这就是我正在尝试但我似乎无法做到的。

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

以下是我在搜索此处时遇到的searchSubArray函数。

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

关于如何实现这一点的任何建议?

0 个答案:

没有答案