PHP - 查找数组的父键

问题描述 投票:0回答:4

我正在尝试找到一种方法来返回数组父键的值。

例如,从下面的数组中我想找出父级的键,其中 $array['id'] == "0002"。 父键很明显,因为它是在这里定义的(它将是“产品”),但通常它是动态的,因此出现了问题。不过,“id”和“id”的值是已知的。

    [0] => Array
        (
            [data] => 
            [id] => 0000
            [name] => Swirl
            [categories] => Array
                (
                    [0] => Array
                        (
                            [id] => 0001
                            [name] => Whirl
                            [products] => Array 
                               (
                                    [0] => Array
                                        (
                                            [id] => 0002
                                            [filename] => 1.jpg
                                         )
                                    [1] => Array
                                        (
                                            [id] => 0003
                                            [filename] => 2.jpg
                                         )
                                )
                         )
                 )
          )
php arrays key parent traversal
4个回答
3
投票

有点粗糙的递归,但它应该可以工作:

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');

2
投票

既然你有一个树结构,那么BFSDFS都可以做到。由于结构是可变的,递归解决方案会很好地工作。当您找到值时,只需返回一个哨兵,然后在调用者中返回键即可。


0
投票

$array = [ "任务" => ["PHP", "HTML", "PYTHON", "JAVASCRIPT", "WORDPRESS"], "分数" => [1, 2, 3, 4, 5], " rates" => ["优秀", "好", "还可以", "差", "非常差"] ]; $array_keys = implode(", ", array_keys($array));回显 $array_keys;


-2
投票
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();

}
© www.soinside.com 2019 - 2024. All rights reserved.