Solved

Why is this loop not working?

Posted on 2011-03-23
10
335 Views
Last Modified: 2012-05-11
I have an array drawn from a database.  It is a series of activities on various dates: I need to display the activities on the appropriate date in a calendar matrix (month view).

Currently, the loop I'm using doesn't work;  I have (with some help) created parts of a multidimensional array that are keyed by "dayofmonth", which is what I need.  But the loop doesn't work at all.  PHP tells me that there are undefined indices (line 6, first chunk) and undefined variables ("$day" & "$act", line 2, second chunk - flagged 31 times for each variable) in the code below.

The code in question is:

$sql = mysql_query("SELECT DAYOFMONTH(a.`date`) AS day, a.`aid`, a.`activityname`, u.`enid` FROM activities a JOIN user_entries u JOIN diaries d ON a.`aid` = u.`aid_FK` AND u.`did_FK` = d.`did` WHERE `mem_no_FK` = 2353 AND a.`date` BETWEEN '2009-07-01' AND '2009-08-01' ORDER BY `date`"));
	
// Reorganise the events into an array keyed by day of the month
$acts = array();
while ($row = mysql_fetch_assoc($sql)) {
	if (!$acts[$row['day']]) $acts[$row['day']] = array();
	$acts[$row['day']] = $row;
}

Open in new window

and
	function insert_acts() {
if ($acts[$day]) {
	foreach ($acts[$day] AS $this_cell) {
		//Clean & display events
		$this_aid = htmlentities($this_cell['aid']);
		$this_actname = htmlentities($this_cell['activityname']);
		$this_enid = htmlentities($this_cell['enid']);
		print "<div><a href=\"CPD_activity_details.php?aid=$this_aid\" class=\"\">$this_actname</a><br /><a href=\"CPD_activity_review.php?enid=$this_enid\" class=\"\">review</a></div>";
	}
	print "</td>";
} else {
	print "</td>";
}
}

Open in new window

Using a test rig, what's stored is:
[acts] => Array
        (
            [6] => Array
                (
                    [day] => 6
                    [aid] => 28244
                    [activityname] => DoH Leadership workshop
                    [enid] => 28336
                )

            [7] => Array
                (
                    [day] => 7
                    [aid] => 28245
                    [activityname] => Timeout and senior team meeting
                    [enid] => 28337
                )

            [15] => Array
                (
                    [day] => 15
                    [aid] => 28246
                    [activityname] => journal club
                    [enid] => 28338
                )

            [17] => Array
                (
                    [day] => 17
                    [aid] => 28247
                    [activityname] => SRSB and RNIB Losing patients event
                    [enid] => 28339
                )

            [22] => Array
                (
                    [day] => 22
                    [aid] => 28248
                    [activityname] => TBI meeting
                    [enid] => 28340
                )

        )

    [row] =>
I'm at a loss.  What does this mean?  And how do I make it work?
0
Comment
Question by:hnmcc
  • 5
  • 3
10 Comments
 
LVL 5

Accepted Solution

by:
tsmgeek earned 500 total points
ID: 35203689
$sql = mysql_query("SELECT DAYOFMONTH(a.`date`) AS day, a.`aid`, a.`activityname`, u.`enid` FROM activities a JOIN user_entries u JOIN diaries d ON a.`aid` = u.`aid_FK` AND u.`did_FK` = d.`did` WHERE `mem_no_FK` = 2353 AND a.`date` BETWEEN '2009-07-01' AND '2009-08-01' ORDER BY `date`"));
        
// Reorganise the events into an array keyed by day of the month
$acts = array();
while ($row = mysql_fetch_assoc($sql)) {
	# this will allow multiple entries per day []
        $acts[$row['day']][] = $row;
}

	function insert_acts() {
#check to see if $acts has been set and is an array
if (isset($acts) && is_array($acts)) {
	# loop each day
	foreach ($acts as $acts_day) {
		# loop though each event for day
                foreach($acts_day as $this_cell){
			//Clean & display events
			$this_aid = htmlentities($this_cell['aid']);
			$this_actname = htmlentities($this_cell['activityname']);
			$this_enid = htmlentities($this_cell['enid']);
			print "<div><a href=\"CPD_activity_details.php?aid=$this_aid\" class=\"\">$this_actname</a><br /><a href=\"CPD_activity_review.php?enid=$this_enid\" class=\"\">review</a></div>";
		}
	}
}

Open in new window

0
 

Author Comment

by:hnmcc
ID: 35205784
Thanks tsmgeek - I like the changes and have adopted them.

But...

Still no data displaying when it should (i.e. on 6, 7, 15, 17, & 22 July 2009).  And still PHP reports "Undefined index" for each of these days, referring to line 4 of the chunk below.

 	// Reorganise the events into an array keyed by day of the month
	$acts = array();
	while ($row = mysql_fetch_assoc($sql)) {
		if (!$acts[$row['day']]) $acts[$row['day']] = array();
		# empty[] allows more than one activity per day
		$acts[$row['day']][] = $row;
	}

Open in new window


And the test rig shows the same variables set - different only in that the intermediate key in Sacts is reinstated.

What is going wrong?
0
 
LVL 5

Assisted Solution

by:tsmgeek
tsmgeek earned 500 total points
ID: 35209062
take line 4 out as you dont need to predefine sub arrays ahead of time, it will be fine
if you want to check an array you need to use is_array() command
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

Author Comment

by:hnmcc
ID: 35210704
Thanks again tsmgeek - the error notices have disappeared, which is a definite improvement!

It seems to me that the problem here is in the test: $day is not being compared to the 'day' value in the acts array.  The test cannot be passed, so the results are never displayed.

I had assumed that the table was working because the </td> tag was being pulled out of the function.  But it wasn't: the browsers (all of them) were rendering the table accurately with unclosed <td> tags throughout.  Which seems to mean that  function insert_acts() is being ignored completely.

This is the code as it stands:
// Reorganise the events into an array keyed by day of the month
$acts = array();
while ($row = mysql_fetch_assoc($sql)) {
	#if (!$acts[$row['day']]) $acts[$row['day']] = array();
	# empty[] allows more than one activity per day
	$acts[$row['day']][] = $row;
}

//Insert activities for day in that day's cell
function insert_acts() {
	# check to see if $acts has been set and is an array
	if (isset($acts) && is_array($acts)) {
		# loop each day
		foreach ($acts as $acts_day) {
			# loop though each event for day
			foreach($acts_day as $this_cell){
				//Clean & display events
				$this_aid = htmlentities($this_cell['aid']);
				$this_actname = htmlentities($this_cell['activityname']);
				$this_enid = htmlentities($this_cell['enid']);
				print "<div><a href=\"CPD_activity_details.php?aid=$this_aid\" class=\"\">$this_actname</a><br /><a href=\"CPD_activity_review.php?enid=$this_enid\" class=\"\">review</a></div>";
			}
		}
	}
#print "</td>";
}

Open in new window


Any thoughts?
0
 
LVL 5

Expert Comment

by:tsmgeek
ID: 35210789
call the function where you then want the divs to be placed
ie
<table>
  <tr><td>
    <?php insert_acts(); ?>
  </td></tr>
</table>

Open in new window


or just take out lines 10 & 26
0
 

Author Comment

by:hnmcc
ID: 35222286
In fact,  insert_acts()  as shown above (or the same code placed directly where it's needed) does NOT work.

We need to check that a matching key is set for each day, as in line 4 below.
if (isset($acts)) {
	if (is_array($acts)) {
		# loop each day
		if (array_key_exists($day,$acts)) {
		# loop though each event for day
			foreach($acts[$day] as $this_cell){
				//Clean & display events
				$this_aid = htmlentities($this_cell['aid']);
				$this_actname = htmlentities($this_cell['activityname']);
				$this_enid = htmlentities($this_cell['enid']);
				print "<div><a href=\"CPD_activity_details.php?aid=$this_aid\" class=\"\">$this_actname</a><br /><a href=\"CPD_activity_review.php?enid=$this_enid\" class=\"\">review</a></div>";
			}
		}
	}
}

Open in new window

0
 

Author Comment

by:hnmcc
ID: 35222480
I intended to give some points to tsmgeek for his(?) assistance - but only some, as I answered the question correctly myself - and not in a way suggested by tsmgeek.
0
 

Author Comment

by:hnmcc
ID: 35222509
Notice: hnmcc has requested that this question be closed by accepting tsmgeek's comment #35203689 (500 points) as the solution and hnmcc's comment #35222286 (0 points) as the assisted solution for the following reason:
PHP array functions...
To cancel this request and generate a request in Community Support for Moderator review, state your reason for objecting and click the 'Object' button. This question will be closed on 3/30/2011 if there are no objections.

I have not requested this.

I want tsmgeek to have some points for trying to help - but NOT all of them, because he/she didn't solve my problem or point me towards a way of solving it.

0

Featured Post

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question