Jump to content

foreach with an array with multiple/two indexes?


galvin

Recommended Posts

This may not make sense and I apologize in advance if it doesn't :) 

 

Anyway, say I have an array with data like this ...

 

$myarray[1]=red;

$myarray[1][animal]=tiger;

$myarray[1][state]=washington;

$myarray[1][food]=pizza;

$myarray[2]=blue;

$myarray[2][animal]=lion;

$myarray[2][state]=california;

$myarray[2][food]=spaghetti;

$myarray[3]=green;

$myarray[3][animal]=cat;

$myarray[3][state]=new york;

$myarray[3][food]=hamburger;

 

How can I do a foreach loop and have all that info available to print out to the browser?  NOTE:  If there is something other than a foreach loop that makes more sense to use in this situation, I'm all ears :)

 

For example, if I want output like...

 

Player 1 -- color: red, animal: tiger, state: washington, food: pizza

Player 2 -- color: blue, animal: lion, state: california, food: spaghetti

Player 3 -- color: green, animal: cat, state: new york, food: hamburger

 

This is what I'm trying to do, but clearly getting nowhere...

	
foreach ( $myarray as ????????) { //and this is where I get lost.  I know how to do it if there is just one index and one value, but I'm getting confused with the two index setup and multiple "types" of values
echo *proper code that will spit out output above*;
}

 

Link to comment
Share on other sites

If you've read the PHP manual page on foreach () you'd notice that all it does is to take the elements of an array, and save them into a variable (as $variable). In the case of a multi-dimensional array, the new variable would become an array in itself.

Printing out the contents of an array, a one-dimensional one in this case, is straight forward. And explained thoroughly in the manual as well.

Link to comment
Share on other sites

If you've read the PHP manual page on foreach () you'd notice that all it does is to take the elements of an array, and save them into a variable (as $variable). In the case of a multi-dimensional array, the new variable would become an array in itself.

Printing out the contents of an array, a one-dimensional one in this case, is straight forward. And explained thoroughly in the manual as well.

 

What he said.

 

But just in case you want code to learn from, here you go :)

 

The two output the exact same thing, but the method is different. First one answers your question directly.

 

<?php
$myarray = array(
array(
	'color'  => 'black',
	'animal' => 'cat',
	'state'  => 'Wyoming',
	'food'   => 'Lasanga'),
array(
	'color'  => 'yellow',
	'animal' => 'lion',
	'state'  => 'Winnipeg', // I'm Canadian. Got a prooblem?
	'food'   => 'Pizza'),
array(
	'color'  => 'green',
	'animal' => 'Giraffe',
	'state'  => 'New York',
	'food'   => 'Potatoes'));

// Let's output this data... simply.
foreach ($myarray as $key=>$player) {
echo 'Player ' . $key . ': ';
echo 'color: ' . $player['color'] . ', ';
echo 'animal: ' . $player['animal'] . ', ';
echo 'state: ' . $player['state'] . ', ';
echo 'food: ' . $player['food'];
echo '<hr />';
}

////////
// The break between outputs... no significance in the code
echo '<br /><br /><br /><br />';
////////

// What if you wanted something a little more... in depth?
class Player // Player class... indivdual player
{
private $number;
private $color;
private $animal;
private $state;
private $food;

function __construct($arr, $num) // The constructor
{
	$this->number = $num;
	$this->color  = $arr['color'];
	$this->animal = $arr['animal'];
	$this->state  = $arr['state'];
	$this->food   = $arr['food'];
}

function getAll() // Return all of the variables, parsed, as a string
{
	$out = 'Player ' . $this->number . ': ';
	$out .= 'color: ' . $this->color . ', ';
	$out .= 'animal: ' . $this->animal . ', ';
	$out .= 'state: ' . $this->state . ', ';
	$out .= 'food: ' . $this->food;

	return $out;
}
}

class Player_Roster // Player_Roster class
{
private $players; // List of player objects

function __construct($players) // Constructor
{
	foreach($players as $key=>$player) { // Create a list of Player objects
		$this->players[] = new Player($player, $key);
	}
}

function getAllToString() // Return all of the player objects, as a string
{
	$out = '';

	foreach($this->players as $player) {
		$out .= $player->getAll();
		$out .= '<hr />';
	}

	return $out;
}
}

$players = new Player_Roster($myarray); // Create the new roster

echo $players->getAllToString(); // Echo the list of players

Link to comment
Share on other sites

@Maxudaskin

 

foreach ($myarray as $key=>$player) {



echo 'Player ' . $key . ': ';
echo 'color: ' . $player['color'] . ', ';
echo 'animal: ' . $player['animal'] . ', ';
echo 'state: ' . $player['state'] . ', ';
echo 'food: ' . $player['food'];
echo '<hr />';
}

 

Why are you echoing "state", "food" etc as literal strings when they are the key values?

 

foreach ($myarray as $data) {
    foreach ($data as $k => $v) {       // apply foreach to inner array
        echo "$k : $v, ";
    }
    echo '<br />';
}

Link to comment
Share on other sites

personally I would only iterate over the parent array and use the inner array key values. it makes it more apparent what is being output when reading the code, IMO.

foreach($myarray as $ID => $data)
{
    echo "Player {$ID} -- color: {$data['color']}, animal: {$data['animal']}, state: {$data['state']}, food: {$data['food']}";
}

 

Of course you could use the indexes of the child array for the labels but it makes it impossible to "see" what field is what in that case.

Link to comment
Share on other sites

@Maxudaskin

 

foreach ($myarray as $key=>$player) {



echo 'Player ' . $key . ': ';
echo 'color: ' . $player['color'] . ', ';
echo 'animal: ' . $player['animal'] . ', ';
echo 'state: ' . $player['state'] . ', ';
echo 'food: ' . $player['food'];
echo '<hr />';
}

 

Why are you echoing "state", "food" etc as literal strings when they are the key values?

 

foreach ($myarray as $data) {
    foreach ($data as $k => $v) {       // apply foreach to inner array
        echo "$k : $v, ";
    }
    echo '<br />';
}

 

I used the literal string keys because it's doubtful that the keys will change.

I think that he's trying to find a way to use the array, not just output everything in it.

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.