Jump to content

Multidimentional Arrays [Creating and Looping for output]


Adamhumbug

Recommended Posts

Hi All,

I have been scouring the internet for a good source that shows how to create an array and loop through it to output it to the page.  I have done this several times but everytime it comes to doing it i have to scratch my head and google to get anywhere near the answer.

I have created a 2 dimentional array of data using the following:

function getExistingAwards(){
	include 'includes/dbconn.php';

	$stmt = $conn -> prepare("SELECT id, award_name, award_year, award_winner from award");
	$stmt -> execute();
	$stmt -> bind_result($id, $an, $ay, $aw);
	$awards = array();
	$out = '';

	while($stmt -> fetch()){
		$awards[$ay] = [$id, $an, $aw]; 
	}
}

This gives me a data structure that looks like this.

Array
(
    [2021] => Array
        (
            [0] => 1
            [1] => Avenue Park Award
            [2] => 1
        )

    [2019] => Array
        (
            [0] => 2
            [1] => Avenue Park Award
            [2] => 1
        )

)

Issue 1 - This looks correct but if there are more than one entries that has the year 2021 for example, only the last one will be added to the array.

Issue 2 - After i have the correct data in the array how do i go about looping through each level of the array. I really struggle with for each loops.

As always, your help is appreciated.

Link to comment
Share on other sites

Your top level array is a list of award years.  Inside each year is a list of winners.  If you want to loop through it all, just use two nested foreach loops.

$awardYearsList = getExistingAwards();
foreach ($awardYearsList as $awardYear => $winnerList){
    echo '<p>Winners in award year '.$awardYear.':</p>';
    foreach ($winnerList as $winner){
        echo '<p>'.$winner[0].' - '.$winner[1].'</p>';
    }
}

 

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.