Arrays

Hi Guys

Need some help here, it cant be that hard, but im just not getting there today :smiley:

Ive an array in an array, basically its an array of town names and references to objects in each town.

the print_r looks like

Array ( [0] => Lannepax [Lannepax] => Array ( [0] => 1190 ) [1] => Demu [Demu] => Array ( [0] => 1190 ) [2] => Nerac [Nerac] => Array ( [0] => 1629 [1] => 1539 [2] => 1996 ) [3] => Condom [Condom] => Array ( [0] => 1629 [1] => 1996 ) [4] => Agen [Agen] => Array ( [0] => 1629 [1] => 1539 [2] => 2125 ) [5] => Lavardac [Lavardac] => Array ( [0] => 1539 ) [6] => Eauze [Eauze] => Array ( [0] => 1996 ) [7] => Valence D'agen [Valence D'agen] => Array ( [0] => 2125 ) [8] => Moissac [Moissac] => Array ( [0] => 2125 ) ) 


I need to read the array and output each town name and ten be able to loop through the objects associated wit the town before moving to the next town.

Ive tried all combinations of foreach that I can think of but none seem to give me the output Im looking for, im thinking of just writing them to a sql table and be done with it, but it cant be that hard to pick the data out of this :blush:

Any pointers appreciated

edit:

Occurs to me that perhaps Im writing the array wrongly so heres the routine im using

if ($town != ''){
 if (in_array($town,$towns)){  // if town name is already in array
  $towns[$town][] = $townrows['Obj_ID'];  // add object number to existing town array

 }else{ // if not already in array, 
  $towns[] = $town; // create
  $towns[$town][] = $townrows['Obj_ID']; // and add object value
 }
}

try this to build your array

if(!empty($town))
{
    if(!array_key_exists($town, $towns))
    {
        $towns[$town] = array();
    }

    $towns[$town][] = $rownrows['Obj_ID'];
}

$towns = array (
'Lannepax' => array( 1190 ),
'Demu' => array ( 1190 ) , 
'Nerac'  => array( 1629 ,1539,1996 ) ,
);

var_dump( $towns);

// gives

array
  'Lannepax' => 
    array
      0 => int 1190
  'Demu' => 
      0 => int 1190
  'Nerac' => 
      0 => int 1629
      1 => int 1539
      2 => int 1996

foreach( $towns as $town=>$v){
echo '<h3 >' . $town . '</h3>' ;
  foreach( $v as $value){
  echo ' -- ' . $value . PHP_EOL ;
  }
}

// gives

Lannepax

-- 1190
Demu

-- 1190
Nerac

-- 1629 
-- 1539 
-- 1996

OT
But no, really, you must live very close to me?

Thanks guys thats sorted me, I can se where I was goig wrong now :slight_smile:

No Cups, not far from you, congrats on the 2011 award :wink: