0

配列の問題について助けが必要です。

最初に、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を想像してください。階層表現が必要です。

編集: サンプル one,two,three には同じ値が含まれていますが、これは実際には当てはまりません-仮定:

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

もちろん、SQL は等しい値を 1、2、3 にまとめてグループ化し、この冗長な情報は役に立ちません。ただし、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));
4

1 に答える 1

0

階層で指定されたフィールドの 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
}
于 2012-08-14T13:30:04.730 に答える