Jump to content

Archived

This topic is now archived and is closed to further replies.

markbett

how to create a multidimensional array

Recommended Posts

when i write
[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];
}
[/code]

Test gets written back out

when i write the code

[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];

[/code]

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?

Share this post


Link to post
Share on other sites
You're clobbering your data each time you do
[code]<?php $guest_array = array($i=>array(${guest_name.$i}, ${guest_email.$i})); ?>[/code]
Try this instead:
[code]<?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>';
?>[/code]

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:
[code]<?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>';
?>[/code]

Ken

Share this post


Link to post
Share on other sites
Markbett,

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

Regards
Huggie

Share this post


Link to post
Share on other sites

×

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.