phparraysmultidimensional-array

How to build a customized 2d array in a loop


I need to build a multidimensional array from records retrieved from my database.

Here is the code I have:

<?php
/*
 ...some code...
 */
foreach($data['colleges'] as $college)
{
  $college_temp[] =  $college->name; 
  $college_temp[] =  $college->abbrev;
  $college_temp[] =  $college->long_name;
  $college_temp[] =  $college->long_abbrev;
  $college_temp[] =  $college->url;
  $college_temp[] =  $college->description;
}

All the records from the database are going one after the other in the array. I need to optimize this using a multidimensional array.


Solution

  • $college_temp = array();
    foreach($data['colleges'] as $college)
    {
        $college_temp[] =  $college;
    }
    
    // Echo the first one's name
    echo $college_temp[0]['name'];
    
    // Echo the second one's url
    echo $college_temp[1]['url'];