James Froggatt
asked on
How to dynamically build a 2D array in PHP
I have an array;
$myArr = array(
array("Uppingham","Rutland ","UK"),
array("Fa","Occitanie","Fr ance"),
array("Puivert","Occitanie ","France" ));
so that
<?echo $myArr [1][0];?>
displays Fa
and
<?echo $myArr [0][3];?>
displays Uk.
What I want to do is dynamically create this array from a database;
My first attempt used the code
when reading this data from a database, but this isn't working.
I have a feeling array_push method will need to be used but all the examples that I see are just about 1D arrays. I've been playing with array_push but just don't seems to be getting it to re-create the array I wish to create at the beginning of my post i.e.;
$myArr = array(
array("Uppingham","Rutland ","UK"),
array("Fa","Occitanie","Fr ance"),
array("Puivert","Occitanie ","France" ));
Please help
Thank you
James
$myArr = array(
array("Uppingham","Rutland
array("Fa","Occitanie","Fr
array("Puivert","Occitanie
so that
<?echo $myArr [1][0];?>
displays Fa
and
<?echo $myArr [0][3];?>
displays Uk.
What I want to do is dynamically create this array from a database;
My first attempt used the code
$myArr = array(array());
int i=0;
while($row=$result->fetch_assoc()){
$myArr[i][0]=$row['city_name_ascii'];
$myArr[i][1]=$row['state_name'];
$myArr[i][2]=$row['country_name'];
i++;
}
when reading this data from a database, but this isn't working.
I have a feeling array_push method will need to be used but all the examples that I see are just about 1D arrays. I've been playing with array_push but just don't seems to be getting it to re-create the array I wish to create at the beginning of my post i.e.;
$myArr = array(
array("Uppingham","Rutland
array("Fa","Occitanie","Fr
array("Puivert","Occitanie
Please help
Thank you
James
ASKER
Yipee!
$myArr = array();
while($row=$result->fetch_assoc()){
$addInfo =[$row['city_name_ascii'],$row['state_name'],$row['country_name']];
array_push ($myArr,$addInfo);
}
Seems to work great. Sorry for waisting your time.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
.. I believe I've worked out a solution for this, I will post once I've tested this.