Search code examples
phparraysloopsforeachincrement

Looping through an array of arrays and creating an array from incremented values


Hello I have a foreach question. I am trying to loop through an array of arrays, and as each array goes through, the values

$alreadyhere = 0;
$nothere = 0;
$addedNewMember = 0;
$addedTagToExistingMember = 0;

will update and increment. At the end of the code, these values get put into the $returnArr Array. What I am trying to do is make a final array called allStats[]; that holds all of the $return[] arrays . I've tried to loop through in different ways and add all the return arrays , but I can't get my head around the logic.

if($newArray){

    $allStats = array();
 
    foreach($newArray as $arrs){

        $alreadyhere = 0;
        $nothere = 0;
        $addedNewMember = 0;
        $addedTagToExistingMember = 0;
    
        foreach($arrs as $arry2){

            //do code and increment values

            $returnArr = [
                'newMembersCount' => $addedNewMember,
                'updatedMembersCount' => $addedTagToExistingMember,
                'existingMembersCount' => $alreadyhere,
                'missingMembersCount' => $nothere,
                'method' => $method
            ];
        
        }
    }
}

What would be the best way to loop through through and create this one array that holds all the return arrays?


Solution

  • You can achieve your desired result by the following code. The inner loop increments the values and the final result is appended to $allStats array in the end.

    $allStats = array();
    if ($newArray) {
        foreach ($newArray as $arrs) {
            $alreadyhere = 0;
            $nothere = 0;
            $addedNewMember = 0;
            $addedTagToExistingMember = 0;
    
            foreach ($arrs as $arry2) {
                //do code and increment values
            }
    
            $allStats[] = [
                'newMembersCount' => $addedNewMember,
                'updatedMembersCount' => $addedTagToExistingMember,
                'existingMembersCount' => $alreadyhere,
                'missingMembersCount' => $nothere,
                'method' => $method
            ];
        }
    }
    
    return $allStats;