我需要一个 array_keys_recursive()

发布于 2024-09-26 11:52:33 字数 270 浏览 6 评论 0原文

$temp = array();
function show_keys($ar)
{
    foreach ($ar as $k => $v )
    {
        $temp[] = $k;
        if (is_array($ar[$k]))
        {
            show_keys ($ar[$k]);
        }
    }

    return $temp;
}

我尝试使用该函数,但它仍然只返回第一个键。

$temp = array();
function show_keys($ar)
{
    foreach ($ar as $k => $v )
    {
        $temp[] = $k;
        if (is_array($ar[$k]))
        {
            show_keys ($ar[$k]);
        }
    }

    return $temp;
}

I tried using that function but it still only returns the first key.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

暗藏城府 2024-10-03 11:52:33

使用 SPL,循环键非常简单(如果您愿意,可以将它们存储在另一个数组中):

<?php
$arr = array_fill(0,8,range(0,3));
var_dump($arr);
foreach( new RecursiveIteratorIterator(
    new RecursiveArrayIterator($arr),
    RecursiveIteratorIterator::SELF_FIRST)
  as $key => $value){
        var_dump($key);
}
?>

Using SPL, looping over the keys is quite easy (store them in another array if you wish):

<?php
$arr = array_fill(0,8,range(0,3));
var_dump($arr);
foreach( new RecursiveIteratorIterator(
    new RecursiveArrayIterator($arr),
    RecursiveIteratorIterator::SELF_FIRST)
  as $key => $value){
        var_dump($key);
}
?>
热鲨 2024-10-03 11:52:33

我在这里看到很多过于复杂的解决方案......

function array_keys_r($array) {
  $keys = array_keys($array);

  foreach ($array as $i)
    if (is_array($i))
      $keys = array_merge($keys, array_keys_r($i));

  return $keys;
}

I see a lot of overly complicated solutions here....

function array_keys_r($array) {
  $keys = array_keys($array);

  foreach ($array as $i)
    if (is_array($i))
      $keys = array_merge($keys, array_keys_r($i));

  return $keys;
}
二手情话 2024-10-03 11:52:33

主要问题是您丢弃了递归 show_keys() 调用的结果。您不对返回值执行任何操作。

评论是内联的。

function show_keys($ar)
{
    // Create new temp array inside function so each recursive call gets
    // a separate instance.
    $temp = array();

    foreach ($ar as $k => $v )
    {
        $temp[] = $k;

        // Use $v instead of $ar[$k].
        if (is_array($v))
        {
            // Combine results of recursive show_keys with $temp.
            $temp = array_merge($temp, show_keys($v));
        }
    }

    return $temp;
}

The main problem is that you are throwing away the results of the recursive show_keys() calls. You don't do anything with the return value.

Comments are inline.

function show_keys($ar)
{
    // Create new temp array inside function so each recursive call gets
    // a separate instance.
    $temp = array();

    foreach ($ar as $k => $v )
    {
        $temp[] = $k;

        // Use $v instead of $ar[$k].
        if (is_array($v))
        {
            // Combine results of recursive show_keys with $temp.
            $temp = array_merge($temp, show_keys($v));
        }
    }

    return $temp;
}
星光不落少年眉 2024-10-03 11:52:33

这可能会起作用吗?

您必须将 $temp 作为全局变量引入,或者从每个递归中获取返回值。我们希望避免全局变量,因此我们将每个递归调用的值与之前收集的值合并。

function show_keys($ar)
{
    $temp = array();
    foreach ($ar as $k => $v )
    {
        $temp[] = $k;
        if (is_array($ar[$k]))
        {
            $temp = array_merge(show_keys ($ar[$k]), $temp);
        }
    }

    return $temp;
}

This might do the trick?

You'd have to either bring in $temp as a global, or pick up the returned value from each recursion. And we'd want to avoid global variables, so we merge the values from each recursion call with previous gathered values.

function show_keys($ar)
{
    $temp = array();
    foreach ($ar as $k => $v )
    {
        $temp[] = $k;
        if (is_array($ar[$k]))
        {
            $temp = array_merge(show_keys ($ar[$k]), $temp);
        }
    }

    return $temp;
}
强者自强 2024-10-03 11:52:33

这个问题不明确,因为您没有指定您的输入和预期输出。

考虑这个示例数组:

$array = [
    'first' => [
        'second' => [
            'third' => 'three',
        ],
        'deuxième' => 'two',
    ],
];

到目前为止,所有其他解决方案都提供了一个扁平的一维数组键列表。

$keys = [
    'first',
    'second',
    'third',
    'deuxième',
];

但是,我需要一个 array_keys_recursive 函数来保留层次结构。

$keys = [
    'first' => [
        'second' => [
            'third',
        ],
        'deuxième',
    ],
];

对于其他寻求类似需求的人,这是我的解决方案:

function array_keys_recursive(array $array) : array
{
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $index[$key] = array_keys_recursive($value);
        } else {
            $index []= $key;
        }
    }

    return $index ?? [];
}

The question is ambiguous because you did not specify your input and expected output.

Consider this example array:

$array = [
    'first' => [
        'second' => [
            'third' => 'three',
        ],
        'deuxième' => 'two',
    ],
];

All of the other solutions so far provide a flattened one-dimensional array list of keys.

$keys = [
    'first',
    'second',
    'third',
    'deuxième',
];

However, I had a need for an array_keys_recursive function that would preserve the hierarchy.

$keys = [
    'first' => [
        'second' => [
            'third',
        ],
        'deuxième',
    ],
];

For anyone else searching for a similar need, here's my solution:

function array_keys_recursive(array $array) : array
{
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $index[$key] = array_keys_recursive($value);
        } else {
            $index []= $key;
        }
    }

    return $index ?? [];
}
未央 2024-10-03 11:52:33

作为其他解决方案的补充,有可能返回扁平数组作为结果,但仍然保留有关树的信息。我们可以将嵌套键与父键连接起来。它对于与其他数组进行比较很有用,因为您可以区分相同的子键但不同的父键

function array_keys_flatten_recursive($array, $parentKey = "") {
    $keys = array_keys($array);
    foreach ($array as $parentKey => $i)
      if (is_array($i)) {
        $nestedKeys = array_keys_flatten_recursive($i, $parentKey);
        foreach($nestedKeys as $index => $key) {
            $nestedKeys[$index] = $parentKey . "." . $key;
        }
        $keys = array_merge($keys, $nestedKeys);
      }
    return $keys;
}

示例:

$array = array(
    "one" => array(
        "one" => "lorem"
    ),
    "two" => array(
        "one" => "lorem"
    )
);


// result : array("one", "two", "one.one", "two.one")

As a supplement for other solutions there is possibility to return flattened array as a result but still keep the information about the tree. We can concatenate nested keys with parent. It could be useful for diffing with other arrays as you are distinguishing between same child keys but different parents

function array_keys_flatten_recursive($array, $parentKey = "") {
    $keys = array_keys($array);
    foreach ($array as $parentKey => $i)
      if (is_array($i)) {
        $nestedKeys = array_keys_flatten_recursive($i, $parentKey);
        foreach($nestedKeys as $index => $key) {
            $nestedKeys[$index] = $parentKey . "." . $key;
        }
        $keys = array_merge($keys, $nestedKeys);
      }
    return $keys;
}

Example:

$array = array(
    "one" => array(
        "one" => "lorem"
    ),
    "two" => array(
        "one" => "lorem"
    )
);


// result : array("one", "two", "one.one", "two.one")
ヅ她的身影、若隐若现 2024-10-03 11:52:33

因为这个函数是无限的。但我的任务是帮助你)

function show_keys($ar, $temp = array())
{    
    if (!empty($ar)) {
    foreach ($ar as $k => $v )
    {
        $temp[] = $k;
        if (is_array($ar[$k]))
        {
            $temp += show_keys($ar[$k], $temp);
        }
    }
    }

    return $temp;
}

Ofcause this function is infinite. But my task is to help you)

function show_keys($ar, $temp = array())
{    
    if (!empty($ar)) {
    foreach ($ar as $k => $v )
    {
        $temp[] = $k;
        if (is_array($ar[$k]))
        {
            $temp += show_keys($ar[$k], $temp);
        }
    }
    }

    return $temp;
}
随心而道 2024-10-03 11:52:33

您的数组 $temp 是全局的。要在您需要的函数中访问 make :

global $temp;

在函数的开头。

目前,该函数的每次调用都会创建一个名为 $temp 的新数组,当您最终从该函数返回到其调用者时,您在第一个函数中创建的 $temp正在返回呼叫,其中只有您的第一层的键。

请注意,使用全局变量并不是好的编程。您需要将数组作为参数传递给递归调用,并通过添加每次迭代中找到的键来修改传递的数组,就像亚历山大和约翰所做的那样。

Your array $temp is global. To make is accessible in the function you need :

global $temp;

at the start of the function.

Currently every invocation of the function is creating a new array with the name $temp and when you finally return from the function to its caller, the $temp you created in your first call is being returned, which has only the keys of your first level.

Note that using global variables is not good programming. You need to pass your array as argument to your recursive calls and modify the passed array by adding keys found in each iterations as Alexander and John have done.

橘虞初梦 2024-10-03 11:52:33
    /**
     * @param array $array
     * @param string $devider
     * @return array
     */
    static public function arrayKeysRecursive(array $array, $devider='.'){
        $arrayKeys = [];
        foreach( $array as $key=>$value ){
            if( is_array($value) ){
                $rekusiveKeys = self::arrayKeysRecursive($value, $devider);
                foreach( $rekusiveKeys as $rekursiveKey ){
                    $arrayKeys[] = $key.$devider.$rekursiveKey;
                }
            }else{
                $arrayKeys[] = $key;
            }
        }
        return $arrayKeys;
    }

使用它

arrayKeysRecursive(['one'=>['two'=>2, 'three'=>['four'=>4]]])

返回

['one.two', 'one.three.four']
    /**
     * @param array $array
     * @param string $devider
     * @return array
     */
    static public function arrayKeysRecursive(array $array, $devider='.'){
        $arrayKeys = [];
        foreach( $array as $key=>$value ){
            if( is_array($value) ){
                $rekusiveKeys = self::arrayKeysRecursive($value, $devider);
                foreach( $rekusiveKeys as $rekursiveKey ){
                    $arrayKeys[] = $key.$devider.$rekursiveKey;
                }
            }else{
                $arrayKeys[] = $key;
            }
        }
        return $arrayKeys;
    }

use it

arrayKeysRecursive(['one'=>['two'=>2, 'three'=>['four'=>4]]])

returns

['one.two', 'one.three.four']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文