matt gooch
matt gooch

Reputation: 101

foreach loop returning 2 values from array

I have a for each loop inside a function that i pass an office region too (101,102), it should loop thorugh the array to get the value in OLevel (Red,Amber,Yellow) of a matching OfficeRegion and return a value.

The issue im having is that only the first row in the array is returning a value and it always returns "#red#red", how can i stop it returning 2 values and make it loop through the entire array?

The array:

array(115) { 
    [0]=> object(stdClass)#93 (2) { ["OfficeRegion"]=> string(3) "101" ["OLevel"]=> string(1) "R" } 
    [1]=> object(stdClass)#94 (2) { ["OfficeRegion"]=> string(3) "102" ["OLevel"]=> string(1) "R" } 
    [2]=> object(stdClass)#95 (2) { ["OfficeRegion"]=> string(3) "103" ["OLevel"]=> string(1) "R" } 
    [3]=> object(stdClass)#96 (2) { ["OfficeRegion"]=> string(3) "201" ["OLevel"]=> string(1) "R" } 
    [4]=> object(stdClass)#97 (2) { ["OfficeRegion"]=> string(3) "202" ["OLevel"]=> string(1) "R" }
    [5]=> object(stdClass)#98 (2) { ["OfficeRegion"]=> string(3) "301" ["OLevel"]=> string(1) "R" } 
    [6]=> object(stdClass)#99 (2) { ["OfficeRegion"]=> string(3) "302" ["OLevel"]=> string(1) "R" } 
    [7]=> object(stdClass)#100 (2) { ["OfficeRegion"]=> string(3) "401" ["OLevel"]=> string(1) "R" } 
    [8]=> object(stdClass)#101 (2) { ["OfficeRegion"]=> string(3) "403" ["OLevel"]=> string(1) "R" } 
}

The for each:

foreach($sqlarray as $index => $columns) {
    foreach($columns as $key => $value) {
        if ($key == 'OfficeRegion' && $value == $OfficeRegion) {
            if($columns->OLevel == "R") {
                return '#red'; 
            } elseif ($columns->OLevel == "O")  {
                return '#amber'; 
            } elseif ($columns->OLevel == "Y")  {
                return '#yellow';
            } else {
                return '#green';
            }
        } elseif ($key == 'OfficeRegion' && $value != $OfficeRegion) {
            return "#green";
        }
    }
}

Any suggestions welcome! thanks

Upvotes: 0

Views: 1078

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

If $OfficeRegion is array, you should rather use code like this and you don't need inner loop here:

foreach($sqlarray as $index => $columns) {

    if (in_array($columns->OfficeRegion, $OfficeRegion)) {

        switch ($columns->OLevel) {
            case 'R':
                echo '#red';
            case 'O':
                echo '#amber';
            case 'Y':
                echo '#yellow';
            default:
                echo '#green';
        }
    } else {
        echo '#green';    
    }
}

I've also changed here return to echo to loop over all items as you probably want.

Upvotes: 1

Related Questions