有一个具有以下表达式的数组 $products[] = $product[$category_id][$product_id]:$products = array( 33 => array( 31 => array( 'model' => 'Product 4', ...
有一个具有以下表达式的数组 $products[] = $product[$category_id][$product_id]
:
$products = array(
33 => array(
31 => array(
'model' => 'Product 4',
'product_id' => 31,
'sku' => '',
'ean' => '1234',
'price' => '80.0000'
),
8733 => array(
'model' => 'qqq',
'product_id' => 8733,
'sku' => '',
'ean' => '1000',
'price' => '344.6281'
)
),
25 => array(
30 => array(
'model' => 'Product 3',
'product_id' => 30,
'sku' => '',
'ean' => '250',
'price' => '50.4132'
),
31 => array(
'model' => 'Product 4',
'product_id' => 31,
'sku' => '',
'ean' => '1234',
'price' => '80.0000'
)
)
);
我需要在 php 中删除重复的产品,结果必须是:
$products = array(
33 => array(
8733 => array(
'model' => 'qqq',
'product_id' => 8733,
'sku' => '',
'ean' => '1000',
'price' => '344.6281'
)
),
25 => array(
30 => array(
'model' => 'Product 3',
'product_id' => 30,
'sku' => '',
'ean' => '250',
'price' => '50.4132'
),
31 => array(
'model' => 'Product 4',
'product_id' => 31,
'sku' => '',
'ean' => '1234',
'price' => '80.0000'
),
)
);
我尝试过这个:
$cleared_products = array();
foreach ($products as $category_id => $category_products) {
foreach ($category_products as $product_id => $product) {
if (isset($cleared_products[$category_id][$product_id])) {
unset($products[$category_id][$product_id]);
} else {
$cleared_products[$category_id][$product_id] = $product;
}
}
}
但不起作用......
编辑以解释为什么我需要 生成 XML 并且任何产品都不能重复。它们属于不同的类别并不重要。XML 收件人规则...
您的代码存在问题,因为您检查了产品是否存在于其类别中。在您的示例中,重复的产品属于两个类别。
我们可以通过跟踪您添加的 ID 轻松地进行调整。
$cleared_products = array();
$productIds = array();
foreach ($products as $category_id => $category_products) {
foreach ($category_products as $product_id => $product) {
if (in_array($product_id, $productIds)) {
continue;
} else {
$productIds[] = $product_id;
$cleared_products[$category_id][$product_id] = $product;
}
}
}
重要提示:你无法控制项目将被过滤到哪个类别
所以预期结果 不 匹配。如果您定义类别的优先级并以此进行排序,则可以在需要的地方将其删除。