Explanation of For each loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kewpe20
Forum Newbie
Posts: 7
Joined: Thu Sep 10, 2009 10:38 am

Explanation of For each loop

Post by kewpe20 »

Hi all,
I have a misunderstanding regarding foreach loops which I can't resolve, nor can I figure out how to get the code right to do what I want.

First I'm storing the results of a Mysql query into an array.
The results contain multiple rows, each row has several that pertain to it-- site_id, site_name, etc.

Code: Select all

 
    // Store all sites to ftp into an array
    $ftp_sites = Array();
    $query =  'SELECT * 
            FROM `'. LOCAL_SITES .'` 
            WHERE ftp = 1';
    $result = mysql_query( $query ) or die(mysql_error());
    while( $row = mysql_fetch_array( $result ) )
    {
        $ftp_sites[] = $row;
    }
 
 
I confirmed that results of the query do exist each with a value in site_id


For each row that was returned I want to run a process, but I get the following messages:
Undefined index: site_id
Invalid argument supplied for foreach()

foreach ($ftp_sites['site_id'] as $key=>$val)
{
//// CODE
}

Can someone explain why $ftp_sites['site_id'] isnt being recognized and /or what approach I should take to resolve
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Explanation of For each loop

Post by requinix »

Code: Select all

$ftp_sites[] = $row;
$ftp_sites is just a list of rows from the query. A site_id will be at $ftp_sites[?]["site_id"].

Code: Select all

foreach ($ftp_sites as $site) {
    echo $site["site_id"];
}
If you want to run a process for each row, why not do it in the while loop you have now? No need for $ftp_sites.
Post Reply