calebe santana
calebe santana

Reputation: 335

Foreach loop over array of objects Laravel

I'm receiving this array of objects and need to iterate over it, but the problem is that I need to get the value of the next item when its iterating, to compare the value of the current object with the next one, and if it's a different value, split this array in two.

So, I was doing it with next() php function:

        //looking for the next register in the array
        $next = next($finances);
        //first array if exist different values
        $aiuaEd = [];
        //second array if exist different values
        $aiua = [];

        foreach ($finances as $finance) {
            if ($finance->cnpj <> $next->cnpj) {
                $aiua[] = $finance;
            } else {
                $aiuaEd[] = $finance;
            }
        }

This code works fine at some point, but then I got this error:

Trying to get property 'cnpj' of non-object in 

I don't know why sometimes works well and sometimes don't, debugging this variables, I found that if my array have 2 objects inside only, when I'm looping over it, the $next->cnpj variable came as empty, and sometimes don't.

Can someone help me with this?

Upvotes: 0

Views: 1848

Answers (1)

calebe santana
calebe santana

Reputation: 335

I solved it with a different approach, instead of using php next(), I first loop over this array saving the cnpj's into an array.

        $cnpjs = [];

        foreach($finances as $finance){
            $cnpj[] = $finance->cnpj; 
        }

Then I use array_unique() to group this 2 differents CNPJ's and sort() to get the correct keys order.

        //grouping cnpjs as unique, should exist only 2 keys 
        $cnpj = array_unique($cnpj);
        //sort array keys to get in order
        sort($cnpj);

Then I iterate over my $finances array again, but now I'm counting if this $cnpj array has more than 2 positions, which means that I have to split this data in two differents arrays.

            foreach($finances as $finance){
            if(count($cnpj) > 1){
                if($finance->cnpj == $cnpj[1]){
                    $aiua[] = $finance;
                }else{
                    $aiuaEd[] = $finance;
                }
            }else{
                $aiuaEd[] = $finance;
            }
        }

I'm pretty sure that this is not the best approach for that problem, or at least the most optimized one, so I'm open for new approach's suggestions! Just posting how I solved my problem in case anyone having the same one.

Notice that this approach is only usable because I know that will not exist more than 2 different's CNPJ's in the array.

Upvotes: 1

Related Questions