我在这里搜索了所有帖子,似乎找不到正确的方法来做我需要的事情。
我有一个通过单个订单从数据库中提取的多维产品数组。
$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;
}
关于我如何实现这一点的任何建议?