如何使用另一个数组中的键递归地构建关联数组?

How can I build an associative array recursively using keys from another array?

好吧,这有点棘手,我碰壁了。

我有一组分组选项:

Array
(
    [0] => Array
        (
            [9] => sum
            [10] => sum
            [11] => avg
        )

    [4] => Array
        (
            [9] => sum
            [10] => sum
            [11] => avg
        )

    [9] => Array
        (
            [9] => sum
            [10] => sum
            [11] => avg
        )

)

我想要得到的是一个如下所示的数组:

Array
(
    [0] => Array
        (
            [4] => Array
                (
                    [9] => Array
                        (
                            [9] => sum
                            [10] => sum
                            [11] => avg
                        )
                )
        )
)

我这个例子只显示了 3 级深度,但我需要它是动态的,因为会有不同的分组选项可用。有些只有 1 个级别,这很容易,但也会有 2 个或更多级别。嵌套级别应始终具有与父级别相同的键。

我正在做的是使用它来迭代数据。键是我正在分组的数据数组中的索引。问题是,我需要较低级别的分组来了解其他索引,因为这对于正确分组多个数据集是必要的。这是为了尝试简化处理大型数据集。我只需要计算最低级别(在此示例中为 9),这样我就可以遍历最终数组来计算每个父分组的分组数据。我将使用键 9 数据构建键 4 数据,使用键 4 数据构建键 0 数据。键需要知道父组的原因是数据对于父组是唯一的。 $a[0][4][9] 与 $a[0]、$a[4]、$a[9] 不同。我需要 9 才能知道它依赖于 4,而 4 依赖于 0。

我不确定 PHP 是否可以做到这一点,或者这是否有意义。你能动态构建这样的数组吗?

正如你所说这将是动态的,首先你需要知道数组的第一个索引,我称之为 $last 因为在循环中是最后使用的索引:

$last = array_search(array_slice($array, 0, 1), $array);

然后在 $temp 中,您将在循环之前和整个循环中保存数组定义。

在循环之后你需要添加你的深度数组的值(在本例中为var_export)并且你需要添加所有的决赛)(在本例中为str_repeat )

$temp .= var_export($array[$last], true) . str_repeat(')', $i);

当你得到最终的字符串(数组定义)时,只需调用 eval

eval($temp . ';');

见代码:

<?php

$array = Array
(
    0 => Array
        (
            9 => 'sum',
            10 => 'sum',
            11 => 'avg'
        ),

    4 => Array
        (
            9 => 'sum',
            10 => 'sum',
            11 => 'avg'
        ),

    9 => Array
        (
            9 => 'sum',
            10 => 'sum',
            11 => 'avg'
        )
);

$last = array_search(array_slice($array, 0, 1), $array);
$temp = "$newArray = ";
$i = 0;

foreach($array as $key => $value) {
  $temp .= "array({$key} => ";
  $last = $key;
  $i++;
}

$temp .= var_export($array[$last], true) . str_repeat(')', $i);

eval($temp . ';');

echo '<pre>';
print_r($newArray);
echo '</pre>';

输出:

Array
(
    [0] => Array
        (
            [4] => Array
                (
                    [9] => Array
                        (
                            [9] => sum
                            [10] => sum
                            [11] => avg
                        )

                )

        )

)

这是另一个递归 'tree',除了它是 'one-way' 而不是 'multi-way'。即它是 'linked list'。 'node data' 仅存储在最终节点中,因为它在每个节点中都是相同的。

像往常一样:Working code at Codepad.org

我发现非常 'interesting' 可以计算出我应该 'initialize' 输出什么以及 'recurse' 输出什么。不管怎样,这是代码...

我决定通过在开始时明确处理一些 'special cases' 来简化代码...

if (count($source) <= 0) {
    return array();
}
elseif (count($source) == 1) {
    return array(key($source) => current($source));
}

接下来,完成工作的函数...

/**
 * Add all nodes to the 'tree'
 *
 * @param type $outNode -- a 'reference' to the current node to be added to
 * @param type $curKey  -- the index of the current node -- need this when overwriting the 'null' value later.
 * @param type $source  -- a reference to the source array as i do not want a copies to be made
 *
 * @return array -- current node
 */
function addNode(&$outNode, $curKey, &$source)
{
    // get the current node details...
    $curKey = key($source);
    $curItems = current($source);

    // advance to the next source node...
    next($source);

    // Is this the final node in the list?
    if (current($source) !== false) { // more nodes to add. We need to recurse...
        $nextKey = key($source);

        $outNode[$curKey] = array($nextKey => null);
        return addNode($outNode[$curKey], $nextKey, $source); // recurse
    }

    // add the items to the last node
    $outNode[$curKey] = $curItems;

    return $outNode;
}

起始条件和构建输出...

// generated tree in here
$outTree = array();

// I use the key(), current() and next() functions as I use the 'internal' array iterator.
$curKey = key($source);
$curItems = current($source);

$outTree[$curKey]  = null; // the 'null' always gets overwritten later.

// build the tree...
$lastNode = addNode($outTree, $curKey,  $source);

// show the output...
echo '<pre>';
print_r($outTree);
echo '</pre>';
exit;

使用提供的数据输出:

Array
(
    [0] => Array
        (
            [4] => Array
                (
                    [9] => Array
                        (
                            [9] => sum
                            [10] => sum
                            [11] => avg
                        )
                )
        )
)