0

この質問の目的は、PHP 多次元配列からデータを出力する最良の方法を見つけることです。

以下の手順をどのように完了することができますか?

私は次の配列を持っています

array1['id']['title']

array2['id']['tags'][]

配列は関数によって生成されていますpg_fetch_array。これにより、要素の各値をその名前またはキーで参照できます。

質問のタイトルとそのタグを取得する手順

私は次のことをしたいと思います

  1. 最初のループ
    1. からタイトルを印刷するarray1[$question_id]
    2. array2[$question_id][]指定された question_id のすべてのタグを出力します
  2. 2 番目のループ
    1. question_idリストの次については、1.1 と同じことを行います。
    2. リストの次のものについては、1.2 と同じことを行いquestion_idます ...
  3. リスト内のすべての $question_ids についてこれを続けます

さまざまな方法を使用して手順を完了できませんでした

  1. 単一の -foreach : merge_unique 内のすべてのアイテムを反復処理できるように多次元配列を作成するには、ここでは十分ではありません。他のマージでも、不要な列が 1 つ削除されます。
  2. whileおよびforeach-sentencesによる 2 つの指定された配列の問題を解決するには: while ループ内に foreach 句があるため、3 つの質問に対して 9 回の反復が行われます。
4

2 に答える 2

1

序文:次の例のいずれも、期待どおりの結果をもたらすはずです。ページを下るにつれて複雑になり、それぞれに独自の利点があります。

まず、関数のベアボーンです。array1 をループして、タイトルを出力します。次に、現在見ているものと同じ ID を持つ array2 から配列を取得し、各値をループして、値を出力します。

foreach($array1 as $id => $sub_array)
{
    echo $sub_array['title'];
    foreach($array2[$id]['tags'] as $tag)
    {
        echo $tag;
    }
}

次に、もう少し明確にします。

 // Go through each question in the first array
 // ---$sub_array contains the array with the 'title' key
 foreach($array1 as $id => $sub_array)
 {
     // Grab the title for the first array
     $title = $sub_array['title'];

     // Grab the tags for the question from the second array
     // ---$tags now contains the tag array from $array2
     $tags = $array2[$id]['tags'];

     // 1.1 Print the Title
     echo $title;

     // 1.2 Go through each tag
     foreach($tags as $tag)
     {
         echo $tag;
     }
 }

必要以上にいくつかのことを行いますが、追加されたステップによってより明確になります。


そして、物事をより複雑にするのが好きだからといって、関数にタイトル/タグの作成を処理させることで、すべてをより適切に分離できます。これにより、foreach ループの混乱が少なくなり、フラストレーションも少なくなります。

// Go through each question in the first array
foreach($array1 as $id => $sub_array)
{
    // Grab the title for the first array
    $title = $sub_array['title'];

    // Grab the tags for the question from the second array
    $tags = $array2[$id]['tags'];

    // 1.1 Print the Title & 1.2 Print the Tags
    create_question($title, $tags);
}

// Functions

// Create all the parts of a question.
function create_question($title, $tags)
{
    create_title($title);
    create_tags($tags);
}

// Print the Title
function create_title($title)
{
    echo $title;
}

// Loop Through Each Tag and Print it
function create_tags($tags)
{
    echo "<ul>";
    foreach($tags as $tag)
    {
        echo "<li>".$tag."</li>";
    }
    echo "</ul>";
}
于 2009-08-16T22:59:16.370 に答える
1

ここで何かが欠けていると確信していますが、...

foreach($array1 as $id => $title) {
  echo $title['title'];
  foreach($array2[$id]['tags'] as $tag) {
    echo $tag;
  }
}
于 2009-08-16T22:59:33.030 に答える