$json = ' [{' id ': "Children": [{"id": "Children": [{"id": 31}]}]},{"id": "Children": [{"id": 29}]},{"id": 32}] ';
$arry = Json_decode ($json, true);
Print_r ($arry);
Echo
";
Print_r (foo ($arry));
Echo
";
function foo ($ar, $level =0, $parent =0,& $res =array ()) {
foreach ($ar as $v) {
$t = Array ();
$v [' level '] = $level;
$v [' parent '] = $parent;
if (Isset ($v [' Children '])) {
$t = $v [' Children '];
unset ($v [' Children ']);
}
$res [] = $v;
if ($t) foo ($t, $level +1, $v [' id '], $res);
}
return $res;
}
?>
Array ([0] = = Array ([id] = [children] = = Array ([0] = = Array ([id] = [children] = = Array ( [0] = = Array ([id] =))) ([1] = = Array ([id] = [children] = = Array ([0] = = Array ([ID] )) [2] = = Array ([id] = 32))
Array ([0] = = Array ([id] = [level] = 0 [Parent] = 0) [1] = = Array ([id] = [level] = 1 [Parent] = [2] = = Array ([id] = [level] = 2 [Parent] = +) [3] = = Array ([ID] + 28 [ Level] = 0 [parent] + 0) [4] = = Array ([id] = [level] = 1 [Parent] = +) [5] = = Array ([i D] = [level] = 0 [parent] + 0))
If that's the case
function foo ($ar, $level =0, $parent =0, $res =array ()) {
foreach ($ar as $v) {
$t = Array ();
$v [' level '] = $level;
$v [' parent '] = $parent;
if (Isset ($v [' Children '])) {
$t = $v [' Children '];
unset ($v [' Children ']);
}
$res [] = $v;
if ($t) foo ($t, $level +1, $v [' id '], $res);
}
return $res;
}
The result is:
Array ([0] = = Array ([id] = [level] = 0 [Parent] = 0) [1] = = Array ([id] = [level] = 0 [Parent] + 0) [2] = = Array ([id] = [level] = 0 [Parent] = 0))
Please combine this example, explain the next value, the difference between the address, thank you.
Reply to discussion (solution)
Value passing:
Copies a copy of the original data for operation without changing the original value.
Reference delivery:
The raw data is manipulated and the original data changes after the operation.
Array value Passing instance code:
Output:array (2) { [0]=> string (1) "A" [1]=> string (1) "B"} Array reference pass
Outpout:array (1) { [0]=> string (2) "DD"}
Consider this: http://www.cnblogs.com/zcy_soft/archive/2011/12/10/2283570.html
$res [] = $v;
if ($t) foo ($t, $level +1, $v [' id '], $res)
----These two statements are inside the function foo, but the principle is the same. As in the example above
The pass value does not affect the original array, and the address will be.
Example:
Address reference
Output:
Array ([0] = 1 [1] = 2 [2] = 3 [3] = 4)
Pass Value
Output:
Array ([0] = 1 [1] = 2 [2] = 3 [3] = 4 [4] = 5)
Array ([0] = 1 [1] = 2 [2] = 3 [3] = 4)
To be blunt, the parameters of a function are copied by default, so that you do not have any effect on the variables that pass through the function when you use it.
Plus & will not replicate, and directly use the
The value of the transfer is more than one copy, not affect each other
Reference is the simultaneous manipulation of the same data, affecting each other