For example, an array includes place names, you already know Shijiazhuang, how to know its superior Hebei. Or you already know Beijing, how to know its superior China
Reply content:
For example, an array includes place names, you already know Shijiazhuang, how to know its superior Hebei. Or you already know Beijing, how to know its superior China
Use ID to make an array of keys each includes parent_id
Recently, I just wrote a copy of the code that gets the depth and parent node of a node in an n-dimensional array.
Class Arrayutil {/** * Depth-first traversal find a tree structure, where a node is located * Parameter example: * $input: [* ' a ' + = [* ' b ' = = [* ' c ' = + [] *] *], * ' d ' = = [*] *] * $target: c * return Values: [3, [' A ', ' B ', ' C ']] * * Can be used with list ($level, $pathKeys) = Self::getnodelevel (...) To use the * $level represents the hierarchy * $pathKeys means that access to this node is required to pass the key * * @param array $input input * @param string $target want to check Find the node (key or value), such as ' F ' * @param array $pathKeys node arrays list * @return Null|array [$level, [$pathKey 0, $pathKey 1, ...] ] will return empty */public static function Getnodelevel (array $input, $target, array $pathKeys = []) {foreach ($input as $key = $val) {$pathKeys [] = $key; if ($key = = $target) {return [count ($pathKeys), $pathKeys]; } elseif (Is_array ($val)) {//The current range does not find a value, recursion goes to the next level $result = Self::getnodelevel ($val, $target, $pathKeys); if ($result) {return $result; }} array_pop ($pathKeys); } return null; }}
Use:
$input = [ 'a' => [ 'b' => [ 'c' => ['hello', 'world'] ] ], 'd' => [ ]];list($depth, $parents) = ArrayUtil::getNodeLevel($input, 'c');print_r($depth); //层级,输出3echo "\n";print_r($parents);/*父级节点,输出Array( [0] => a [1] => b [2] => c)*///获得目标节点的子数组$target = &$input;foreach ($parents as $key) { $target = &$target[$key];}print_r($target);/*输出子节点Array( [0] => hello [1] => world)*/
Where's the code?