For the non-recursive tree array constructor issued by the xuzuning moderator, you have used loops or recursion to build a tree array. When searching today, we can see the non-recursive tree-type array building function issued by the xuzuning moderator. PHPcode *** create a subnode tree array * parameter * $ ar array, data organized in the list of neighboring items * $ the subscript or associated key name as the primary key in the id array * $ the subscript of the parent key in the pid array. about the non-recursive tree array constructor issued by the xuzuning moderator problem
Previously, I used loops or recursion to build a tree array. When searching today, we can see the non-recursive tree-type array building function issued by the xuzuning moderator.
PHP code
/*** Create a subnode tree array * parameter * $ ar array, data organized in the list of Joins * $ the subscript or associated key name of the primary key in the id array * $ the subscript or associated key name of the parent key in the pid array * returns a multi-dimensional array **/ function find_child ($ ar, $ id = 'id', $ pid = 'pid ') {foreach ($ ar as $ v) $ t [$ v [$ id] = $ v; foreach ($ t as $ k =>$ item) {if ($ item [$ pid]) {$ t [$ item [$ pid] ['child '] [$ item [$ id] = & $ t [$ k] ;}} return $ t ;}
I think that writing is very clever, efficient, secure, and beneficial. However, in actual use, I encountered a small problem.
Because the central idea of this function is to store it through a structure like $ tree [$ pid], that is, the key of each record is its $ pid.
In this case, a problem occurs. when I use json_encode (),
{"Pid1": {"id": "0001", "pid": "0000", "children": [{"pid2": {"id ": "0002", "pid": "0001" }}, {"pid3": {"id": "0003", "pid ": "0001 "}}] }}
However, the structure I need is
{"Id": "0001", "pid": "0000", "children": [{"id": "0002", "pid": "0001 "}, {"id": "0002", "pid": "0001"}]}
That is to say, the key for storing records is the default value of array.
How can I modify this function?
------ Solution --------------------
Not likely, unless you look for new algorithms
This algorithm uses the relationship between pid and id to construct an associated array.
If you want to use this function, you must accept this result. You can remove the child key.
If you traverse the result, you can use array_values to convert the associated arrays of all child objects into subscript arrays. this is also a method.