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
https://forums.phpfreaks.com/topic/21014-how-to-create-a-multidimensional-array/
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

Archived

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

×
×
  • 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.