Php recursion achieves unlimited classification php formatted array
-
// The mysql PDO used by the database is the same as the whole idea.
- $ Conn = mysql_connect ('localhost', 'root', '123 ');
- If (mysql_errno ()){
- Printf ('connection failed'. mysql_error ());
- }
- Mysql_select_db ('edeng ');
- Mysql_set_charset ('utf8 ');
- /*
- * Recursive functions
- * @ Param id: to query all fid = $ id sub-classes, set the default value of $ id to 0 because I set the fid of the top-level category to 0 in the database.
- */
- Function get_array ($ id = 0 ){
- $ SQL = "select id, fid, cname from e_cat where fid = $ id ";
- $ Result = mysql_query ($ SQL );
- $ Arr = array ();
- If ($ result & mysql_affected_rows ()){
- While ($ rows = mysql_fetch_assoc ($ result )){
-
$ Rows ['child '] = get_array ($ rows ['id']);
- $ Arr [] = $ rows;
- }
- Return $ arr;
- }
- }
- Echo'
'; - $ Result = get_array ();
- Print_r ($ result );
The function first queries all classes whose fid is 0. Call back one by one while to find the subclass whose fid is the id of the current class.
|