We help IT Professionals succeed at work.

How to dynamically build a 2D array in PHP

James Froggatt
on
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
Comment
Watch Question

Author

Commented:

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

Author

Commented:

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.

 
 $myArr = array();    

while($row=$result->fetch_assoc()){      

$addInfo =[$row['city_name_ascii'],$row['state_name'],$row['country_name']];    
array_push ($myArr,$addInfo);    

}