如何从另外两个数组(如“分组依据”)中构建分层关联数组


How to build a hierarchical associative array out of two other arrays like "group by"

我需要数组问题的帮助。

首先,我有一个数组,就像你从sql查询中收到的一样:

$aRows=array(
  array("one" => 1, "two" => 2, "three" => 3, "a" => "4", "b" => "lala"),
  array("one" => 1, "two" => 2, "three" => 3, "a" => "5", "b" => "lolo"),
  array("one" => 1, "two" => 2, "three" => 3, "a" => "6", "b" => "lili")
)

然后我有另一个定义层次结构的数组 - 让我们说

$aArray=array("one", "two", "three");

现在我想构建一个分层关联数组:

$newArray = 
  array(
    "one" => array(
      "two" => array(
        "three" => array(
          array("a" => "4", "b" => "lala"),
          array("a" => "5", "b" => "lolo"),
          array("a" => "6", "b" => "lili"),
        )
      )
    )
  ); 

想象一个"分组依据"sql,我想要分层表示。

编辑:在样本一,二,三包含相同的值,这在现实生活中并非如此 - 假设:

select one,two,three,a,b from a_table group by one,two,three;

当然,SQL会将等于一,二,三的值组合在一起,这些冗余信息是无用的。但是sql不能显示分层数据,所以字段是多余的。

编辑2:感谢Waygood,完整的解决方案是:

$aRows=array(
    array("one" => 1, "two" => 2, "three" => 3, "a" => "4", "b" => "lala"),
    array("one" => 1, "two" => 2, "three" => 4, "a" => "5", "b" => "lolo"),
    array("one" => 1, "two" => 2, "three" => 4, "a" => "6", "b" => "lili")
);
$aArray=array("one", "two", "three");
$output=array();
foreach($aRows as $row)
{
    $newKey = "";
    foreach($aArray as $key) // loop through the hierarchy to get the fields names
    {
        eval('$exist = array_key_exists(''' . $row[$key] . 
        ''', $output' . $newKey . ');');
        if (!$exist)
        {
            $newKey .= "['" . $row[$key] . "']";
            eval('$output' . $newKey . '=array();');
        }
    }
    eval('$output' . $newKey . '[]=$row;');
}
echo(var_export($output, true));

如果要使用层次结构中指定的字段的 VALUES,您可以:

$output=array();
foreach($aRows as $row)
{
    reset($aArray);
    $eval='$output';
    foreach($aArray as $key) // loop through the hierarchy to get the fields names
    {
        if(is_numeric($row[$key]))
        {
           $eval.='['.$row[$key].']';  // build the key based on the number $row value of each field named
        }
        else
        {
           $eval.='['''.$row[$key].''']';  // build the key based on the string $row value
        }
        unset($row[$key]); // remove the field from the $row
    }
    $eval.='=$row;';
    eval($eval);  // evaluate the built up index and set it to the remaining data
}