Jump to content

Looping through an array of arrays with a foreach loop


AdRock
Go to solution Solved by 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
    }
Edited by AdRock
Link to comment
Share on other sites

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.

Edited by Ch0cu3r
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.