skahan
12/18/2013 - 6:54 PM

Make and loop through nested associative array

Make and loop through nested associative array

<?php
$strQuery = "SELECT pa_date, holdingnum, val10k FROM positions_price_archive ";
$strQuery .= "WHERE (holdingnum = 1 OR holdingnum = 2 OR holdingnum = 3) AND pa_date != '0000-00-00' ";
$strQuery .= "ORDER BY pa_date ASC";
//2012-12-18,1.0000,100000
$result = $connect->query($strQuery);

//Create nested assoc array
$insertArray = array();
while ($row = $result->fetch_assoc()){
  $insertArray[$row['pa_date']][$row['holdingnum']] = $row['val10k'];
}
// var_dump($insertArray);
//  '2002-03-28' => 
//    array (size=3)
//      '1.0000' => string '10000.00000' (length=11)
//      '2.0000' => string '10000.00000' (length=11)
//      '3.0000' => string '10023.58000' (length=11)
//  '2002-04-01' => 
//    array (size=3)
//      '1.0000' => string '10000.00000' (length=11)
//      '2.0000' => string '10000.00000' (length=11)
//      '3.0000' => string '10016.00000' (length=11)
//etc.

//loops through and echo values
foreach ($insertArray as $key => $value){
  echo $key.' '.$value['1.0000'].' '.$value['2.0000'].' '.$value['3.0000'];
  echo "<br/>";
}
//2002-03-28 10000.00000 10000.00000 10023.58000
//2002-04-01 10000.00000 10000.00000 10016.00000
//2002-04-02 10000.00000 10000.00000 9930.77000
//2002-04-03 10000.00000 10000.00000 9833.24000
//2002-04-04 10000.00000 10000.00000 9840.81000
?>