[thelist] How to store data in multidimensional array in a loop (PHP)
Darrell King
darrellgking at gmail.com
Wed Sep 19 08:00:42 CDT 2007
Simplify it while you are debugging:
foreach ($row= mysql_assoc($result)) {
$data[$row['reg_name']][$row['year']] = $row['popt'];
}
To spit them back out:
foreach($data as $reg_name => $year_arrays) {
echo "<strong>$reg_name:</strong><br/>\n";
foreach ($year_arrays as $year => $popt) {
echo " $year: $popt<br/>\n";
}
}
The key is to use the field names as the array keys. Keeps things simple and
easily visualized, IMHO.
D
On 9/19/07, Stefan Schwarzer <st.schwarzer at geois.de> 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
> --
>
> * * Please support the community that supports you. * *
> http://evolt.org/help_support_evolt/
>
> For unsubscribe and other options, including the Tip Harvester
> and archives of thelist go to: http://lists.evolt.org
> Workers of the Web, evolt !
>
--
Darrell G. King
DarrellGKing at gmail.com
(C) 1/585.820.8231
More information about the thelist
mailing list