prc
prc

Reputation: 187

How to distinct values on foreach loop

In my collection I have some foreach that returns some id's BUT not as an array so array_unique() doesn't work in my case. I want to distinct the returned values.

foreach ($prodCollection as $prod) {
    $catCollection = getModel()...; //$prod i need it in my collection
    foreach ($catCollection as $col) {
        var_dump($col->getId());
    }
} 

Result:

string(4) "5510"

string(4) "5510"

What I need is is string(4) "5510" just once.

Upvotes: 0

Views: 1394

Answers (3)

prc
prc

Reputation: 187

I just getting this solution as a workaround, It do the trick I don't know if it's the better one !

$groupValues = array();
foreach ($prodCollection as $prod) {
    $catCollection = getModel()...; //$prod i need it in my collection
    foreach ($catCollection as $col) {
        array_push($groupValues, $colt->getId());
        var_dump($col->getId());
    }
} 

var_dump(array_unique($groupValues)); // return 5510

Upvotes: 0

Nidhin
Nidhin

Reputation: 1838

Use array with keys. Put your values as keys in the array. It give same effect as Set

$set1 = array ('a' => 1, 'b' => 1, );

or

add the items to an array, then call array_unique to remove duplicates

Upvotes: 0

Virb
Virb

Reputation: 1578

You can do it like this way.

Check if value is in array or not, if not then add it in array. That may help.

$result = array();
foreach ($prodCollection as $prod) {
    $catCollection = getModel()...; //$prod i need it in my collection
    foreach ($catCollection as $col) {
        if(!in_array($col->getId(), $result)){  // Check if value is in array or not, if not then add it in array.
            $result[]=$col->getId();
        }
        //var_dump($col->getId());
    }
} 

Upvotes: 1

Related Questions