这是我的宝座
<?php
foreach ($_productCollection as $_product){
echo "<PRE>";
print_r($_product->getData());
}
?>
foreach数组输出:-
Array
(
[entity_id] => 85
[name] => Round Bur
)
Array
(
[entity_id] => 86
[name] => testile Bur
)
Array
(
[entity_id] => 87
[name] => Shovel
)
Array
(
[entity_id] => 88
[name] => Round Bur
)
例如,我想在foreach下删除相同的名称数组
实际输出
Array
(
[entity_id] => 85
[name] => Round Bur
)
Array
(
[entity_id] => 86
[name] => testile Bur
)
Array
(
[entity_id] => 87
[name] => Shovel
)
由于相同的名称,如何删除最后1个数组。请给我一个解决方案
答案 0 :(得分:2)
您可以将所有结果放入一个数组中,仅在name
不存在的情况下添加它们:
$products = array();
foreach ($_productCollection as $_product){
$product = $_product->getData();
if (!in_array($product['name'], array_column($products, 'name'))) {
$products[] = $product;
}
}
echo "<PRE>";
print_r($products);
答案 1 :(得分:2)
您可以拼接包含相同值的重复行:
$res_ar = []; // resultant array
$ar_names = []; // array of unique names
foreach($ar as $ind => $row){
if (in_array($row['name'],$ar_names)){ // if name was before
array_splice($ar,$ind,1); // remove element by its index
} else {
$ar_names[] = $row['name']; // add new name to the unique array of names
$res_ar[] = $row; // saving row with new name value
}
}
您的案例的执行如下:
$res_ar = [];
$ar_names = [];
foreach ($_productCollection as $ind => $_product){
$row = (array)$_product->getData();
if (in_array($row['name'], $ar_names)){
array_splice($_productCollection,$ind,1);
} else {
$ar_names[] = $row['name'];
$res_ar[] = $_product;
}
}
答案 2 :(得分:1)
最后一个版本,只需跟踪添加的名称,还可以将原始名称添加到输出中,而不是数据数组中。
$output = [];
$existingNames = [];
foreach ($_productCollection as $product){
$productName = $product->getData()['name'];
if ( !isset($existingNames[$productName])) {
$existingNames[$productName] = true;
$output[] = $product;
}
}