[thelist] How to store data in multidimensional array in a loop (PHP)
Bojan Tesanovic
btesanovic at gmail.com
Wed Sep 19 07:44:36 CDT 2007
Stefan Schwarzer wrote:
Hey there, so for this kind of stuff I would suggest using simple class to wrap
data you have from an sql query
here is sample class (PHP5) but it can be easily rewritten to PHP4
<?php
class RegionWrapper{
public $region;
public $yearToPop = array();
public function __construct($reg_name=null){
$this->region = $reg_name;
}
public function addYearPop($year,$pop){
$this->$yearToPop[$year] = $pop;
}
public function getRegion(){
return $this->region;
}
public function getData(){
return $this->yearToPop;
}
}
$sumData = array();
$rs = mysql_query($sql);
while ($row = mysql_fetch_assoc($rs)){
//you will have now variables from keys of $row array
//eg if $row['reg_name'] = 'Africa' you will have
//echo $reg_name; will output Africa also in PHP4
extract($row);
if( isset($sumData[$reg_name]) ){
$_rw = $sumData[$reg_name];
}else{
$_rw = new RegionWrapper($reg_name);
}
$_rw->addYearPop($year,$popt);
$sumData[$reg_name] = $_rw;
}
//list results
foreach ($sumData as $rwObject){
echo $rwObject->getRegion(); //or access it $rwObject->region
foreach ($rwObject->getData() as $year=>$pop){
echo "$year : $pop <br/>";
}
}
?>
This is not tested but it should work fine.
> Hi there,
>
> I need to store three pieces of data - a result of a SQL query - in a
> multidimensional array, but don't really succeed. Sometimes it works,
> but then the output doesn't work accordingly.
>
> My SQL result comes with something like this:
> Code: ( text )
> Africa | y2000 | 9430
> Africa | y2005 | 9678
> Europe | y2000 | 2314
>
> where there are 6 regions and multiple years.
>
> Last thing I came up with was this for stocking the data in the array:
> Code: ( php )
> $sum_pop_total_dataset[] = array($row['reg_name'] => array($row
> ['year'], $row['popt']));
>
>
> That seemed to work. But then the output function went a bit wrong:
> Code: ( php )
> while (list($key1) = each ($sum_pop_total_dataset))
> {
> echo "<br />key1: ".$key1;
> while (list($key2, $value) = each ($sum_pop_total_dataset[$key1]))
> {
> echo "<br />key2: ".$key2." value: ".$value[0];
>
> }
> }
>
>
> Code: ( html4strict )
> key1: 0
> key2: North America value: y_2005
> key1: 1
> key2: Europe value: y_2005
> key1: 2
> key2: Asia + Pacific value: y_2005
>
>
> So, it seemed that the allocation of the SQL result to the principal
> variable didn't work correctly. But if I take the [] away from
> $sum_pop_total_dataset[]*= ..., than the variable is being re-
> initialized at each time.
>
> Can someone give me a hint what I should do?
>
> Thanks a lot!
>
> Stef
--
Bojan Tesanovic
http://www.classicio.com/
http://www.real-estates-sale.com/
More information about the thelist
mailing list