Jump to content


Photo

how to create a multidimensional array


  • Please log in to reply
2 replies to this topic

#1 markbett

markbett
  • Members
  • PipPipPip
  • Advanced Member
  • 133 posts

Posted 16 September 2006 - 11:04 PM

when i write
$i='1';
		$guest_array = array();
		$guests=3;
		$guest_name1="test";
		$guest_email1="tesingt@blah";
		$guestnum3="tessafasfd sdft";
		//$guests=mysql_real_escape_string($_POST['guests']);
		while($i<=$guests){
		echo "i am writing to array";
			$guest_array = array($i=>array(${guest_name.$i}, ${guest_email.$i}));
			$i++;
			echo $guest_array[1][0];
			}

Test gets written back out

when i write the code

$i='1';
		$guest_array = array();
		$guests=3;
		$guest_name1="test";
		$guest_email1="tesingt@blah";
		$guestnum3="tessafasfd sdft";
		//$guests=mysql_real_escape_string($_POST['guests']);
		while($i<=$guests){
		echo "i am writing to array";
			$guest_array = array($i=>array(${guest_name.$i}, ${guest_email.$i}));
			$i++;

			}
				echo $guest_array[1][0];
	

and i move the echo outside the loop then i dont get the information i want back out... this leads me to believe that the array data is being overwritten.... how do i write to the array in a different key?

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 16 September 2006 - 11:27 PM

You're clobbering your data each time you do
<?php $guest_array = array($i=>array(${guest_name.$i}, ${guest_email.$i})); ?>
Try this instead:
<?php
$i=1;
$guest_array = array();
$guests=3;
$guest_name1="test";
$guest_email1="tesingt@blah";
$guestnum3="tessafasfd sdft";
for($i=1;$i<=$guests;$i++){
	echo "i am writing to array";
	$guest_array[$i] = array(${guest_name.$i}, ${guest_email.$i});
}
echo '<pre>' . print_r($guest_array,true) . '</pre>';
?>

If you can, you probably want to change your variables $guest_name<n> and $guest_email<n> to be arrays also, the the loop would become:
<?php
$guest_array = array();
for ($i=0;$i<count($guest_name);$i++)
     $guest_array[] = array($guest_name[$i],$guest_email[$i]);
echo '<pre>' . print_r($guest_array,true) . '</pre>';
?>

Ken

#3 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 17 September 2006 - 01:57 PM

Markbett,

I replied to your other post about this too, take a look back at that one as well.

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users