Jump to content

Looping through an array of arrays with a foreach loop


AdRock

Recommended Posts

I have this array which has been pulled from a MySQL database (did a var_dump)

array(2) {
  [0]=>
  array( {
    ["id"]=>
    string(1) "3"
    [0]=>
    string(1) "3"
    ["title"]=>
    string(23) "New Venture Coming Soon"
    [1]=>
    string(23) "New Venture Coming Soon"
    ["archived"]=>
    string(1) "y"
    [2]=>
    string(1) "y"
    ["postdate"]=>
    string(14) "7th March 2009"
    [3]=>
    string(14) "7th March 2009"
  }
  [1]=>
  array( {
    ["id"]=>
    string(1) "4"
    [0]=>
    string(1) "4"
    ["title"]=>
    string(22) "Visit To Headley Court"
    [1]=>
    string(22) "Visit To Headley Court"
    ["archived"]=>
    string(1) "y"
    [2]=>
    string(1) "y"
    ["postdate"]=>
    string(14) "7th March 2009"
    [3]=>
    string(14) "7th March 2009"
  }
}

I want to loop through the array and display the information but if $not_archived equals to zero then it displays a message.

 

The problem is that it displays the message becuase $not_archived is equal to zero

$z = 0;
    $not_archived = 0;

    foreach($news as $newsitem) {
        if($newsitem['archived'] == 'N') {
            if($z % 2==0) {
                //<tr class="yellow">
                $z++;
            }
            else {
                //<tr class="white">
                $z++
            }
            $not_archived++;
            
            echo $newsitem['id'];
            echo $newsitem['title'];
        }
    }

    if($not_archived == 0) {
        //No active news in database
    }

Because you are only incrementing the $not_archived variable when the current news item's archived field is set to N ($newsitem['archived']). The var_dump you posted contains two news items and both have the archived field set to y.

Why don't you query for those WHERE archive = 'N' ?

 

If you have to store in array, use fetch_assoc() and not fetch_array(). As you may have noticed, fetch_array() gets all the values twice.

 

EG

while ($row = $db->fetch_assoc()) {
    $array[] = $row;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.