PHP - Find parent key of array

安稳与你 提交于 2019-11-27 05:28:22

A little crude recursion, but it should work:

function find_parent($array, $needle, $parent = null) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $pass = $parent;
            if (is_string($key)) {
                $pass = $key;
            }
            $found = find_parent($value, $needle, $pass);
            if ($found !== false) {
                return $found;
            }
        } else if ($key === 'id' && $value === $needle) {
            return $parent;
        }
    }

    return false;
}

$parentkey = find_parent($array, '0002');

Since you have a tree structure either of a BFS or DFS can do it. Since the structure is variable a recursive solution would work well. Simply return a sentinel when you find the value, then return the key in the caller.

chla
function array_to_xml($array, $rootElement = null, $xml = null) {

    $_xml = $xml;

    if ($_xml === null) {
        $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>');
    }

    $has_int_key = 0;

    foreach ($array as $k => $v) {
        if (is_array($v)) {
            if(is_int($k)){
                $this->array_to_xml($v, $k, $_xml->addChild($rootElement));
            } 
            else {
                foreach($v as $key=>$value) {
                    if(is_int($key)) $has_int_key = 1;
                }

              if ($has_int_key) {
                  $this->array_to_xml($v, $k, $_xml);
              } else {
                  $this->array_to_xml($v, $k, $_xml->addChild($k));
              }
            }
        } 
        else {
            $_xml->addChild($k, $v);
        }
    }

    return $_xml->asXML();

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!