Grouping cities, states and countries in MYSQL PHP -
I am new to PHP and have seen many sites for it but are not able to understand properly.
I have this question:
$ result = mysql_query ("country, state, city select country by country, state, city, state Select ") or die (mysql_error ()); This sample data is given below:
Canada - State 1 - City Apple
Canada - State 2 - City Grape
Canada - State 1 - City Apple
Canada - State 2 - City Coffee
USA - State 1 - City Zebra
USA - State 2 - City Cat
USA - State 2 - City Lion
USA - State 3 - City Bird
USA - State 1 - City Zebra
My goal is to create a group of cities under the respective state and count city, Nbndit group of states and groups within the State; Group (1), City Grapes (1)} United States - {State 1 - City Zebra (2) State 2 - City Cat (1), City Sher (1) State 3 - City Bird (1)}
From another site, I found this:
$ combined result = array (); ($ Rec = mysql_fetch_assoc ($ result)) {$ United Result [$ rec ['country']] [] = array ('s' => $ rec ['state'], 'c' = & gt; ; $ Rec ['city']); } Foreach (array_keys ($ combinedResults) as country $) {echo '& lt; Div class = "country" & gt; $ Country '& Lt; / Div & gt; '; Br / & gt; & Lt; Br / br / & gt; $ Set ['c']. & Lt; Br / & gt; & Gt; '; }} These groups are only equal countries and not state and cities. I think the above part of the code is trying to pre-process the data in any type of multi-dimensional array and the results of the loop are displayed for it. I can not understand it clearly.
Would I be very grateful if somebody could explain it to me and how can I extend the states and cities even after this?
The SQL question will give you a set of results with fixed columns. In your example, there is a variable number of columns (count of multiple cities), so this will not work.
You can use COUNT and GROUP BY in SQL to get something
Country State Cities Canada State 1 4 Canada State 2 3 USA State 2 2 etc., but you'll have a duplicate in the left-hand column.
To get rid of duplicates, to make the loop on such a multi-dimensional array like Ex> $ country = array (); Foreign exchange ($ $ as the result of the result) {if (! Isset ($ country [line-> country])) {$ country [$ line-> Country] = array (); } $ Countries [row-gt; Country] [row-gt; State] = $ row-> Number of cities; } Alternatively, you can resume the stuff instead. You can either get all the other results in this way on the whole set, or you can break it in small questions and make one per country or one state. Be careful, however, that the kitens (and DB display) are killed by putting SQL in the loop :).
Comments
Post a Comment