Jump to content

how to create a multidimensional array


markbett

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?
Link to comment
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
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.