0

Here is my foreach

<?php 
    foreach ($_productCollection as $_product){
        echo "<PRE>";
        print_r($_product->getData());
    } 

    ?>

foreach Array Output:-

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

)

I want to remove the same name array under foreach for example

Actual Output

Array
(
    [entity_id] => 85
    [name] => Round Bur

)
Array
(
    [entity_id] => 86
    [name] => testile Bur

)
Array
(
    [entity_id] => 87
    [name] => Shovel

)

How to remove the last 1 arrays because of a name as same. please give me a solution

Devidas
  • 181
  • 1
  • 11

3 Answers3

2

You can put all the results in an array, only adding them if the namedoesn't already exist:

$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);
Nick
  • 138,499
  • 22
  • 57
  • 95
2

You can splice repeated row which contains the same value:

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

Demo

Implementation for your case looks like next:

$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;
       } 
}
Aksen P
  • 4,564
  • 3
  • 14
  • 27
1

One last version, just keep a track of the names added, but also add the original to the output rather than the array of data...

$output = [];
$existingNames = [];
foreach ($_productCollection as $product){
    $productName = $product->getData()['name'];
    if ( !isset($existingNames[$productName]))  {
        $existingNames[$productName] = true;
        $output[] = $product;
    }
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Weird considering it essentially works the same way as the second answer which got an upvote. happy to compensate... – Nick Nov 20 '19 at 12:23
  • @Nick, thanks, it's more of a case if there is something wrong with my code I'd rather people say. Although sometimes it may be someone messing around :-/ – Nigel Ren Nov 20 '19 at 12:26
  • I couldn't agree with you more. But for the most part that doesn't seem to be how SO works... – Nick Nov 20 '19 at 12:48