Link to home
Start Free TrialLog in
Avatar of James Froggatt
James FroggattFlag for France

asked on

How to dynamically build a 2D array in PHP

I have an array;

$myArr = array(
array("Uppingham","Rutland","UK"),
array("Fa","Occitanie","France"),
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

$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++;
}

Open in new window


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","France"),
array("Puivert","Occitanie","France"));


Please help

Thank you
James
Avatar of James Froggatt
James Froggatt
Flag of France image

ASKER

.. I believe I've worked out a solution for this, I will post once I've tested this.

Yipee!


$myArr = array(); 
 
while($row=$result->fetch_assoc()){ 
 
  $addInfo =[$row['city_name_ascii'],$row['state_name'],$row['country_name']]; 
  array_push ($myArr,$addInfo); 
 
}

Open in new window


Seems to work great. Sorry for waisting your time.

ASKER CERTIFIED SOLUTION
Avatar of James Froggatt
James Froggatt
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial