is said to be a Baidu PHP face test, has given an array:
$arr = Array (' B ' => ' A ', ' C ' => ' a ', ' E ' => ' B ', ' d ' => ' B ', ' F ' => ' C ', ' G ' => ' e ', ' h ' => ' f ');
Write an algorithm that completes the conversion to the following format:
array ( ' a ' => array ( ' B ' => array ( ' E ' => array ( [0] => ' G ', ), [0] => ' d ', ), ' C ' => array ( ' F ' => array ( [0 ] => ' h ', ), ), )
This structure should belong to a trie tree. At the time of writing, because I did not find the second parameter of the Array_keys () function (Khan one first), and then wrote the following method to achieve.
Function getsomething (& $arr, & $re, $c = ") { $c or //Mark set to True while ($k when there is a key corresponding to $c = array_
Search ($c, $arr)) { //Loop gets the key with the value $c. getsomething ($arr, $re [$c], $k); // unset ($arr [$k]) until the last time there is no key corresponding; //removal This element is no longer used $
flag = true;    &NBSP} //the normal existing key before the flag is true description, does not continue to generate the elements of the [0] subscript if (! $flag) return $re [] = $c; }//Call getsomething ($arr, $re, ' a ');
The
, though a bit of a miracle, is at least implemented. Here is another solution for a netizen using Array_keys ():
function _array_keys ($k, $arr) {
$return = array ();
if ($ret = Array_keys ($arr, $k)) {
foreach ($ret as $v) {
if ($t = _array_keys ($v, $arr)) {
$return [$v] = $t;
else {
$return [] = $v;
}} return
$return;