[thelist] How to store data in multidimensional array in a loop (PHP)
Phil Turmel
pturmel-webdev at turmel.org
Wed Sep 19 06:03:41 CDT 2007
Stefan Schwarzer wrote:
> 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
Hi Stef,
You need to specify the keys you want to store inside the []s, like this:
$sum_pop_total_dataset[$row['reg_name']][$row['year']] = $row;
This also leaves the original key names, so you would use:
$value['year'] and $value['popt'] instead of $value[0] and $value[1].
HTH,
Phil
More information about the thelist
mailing list