序文:次の例のいずれも、期待どおりの結果をもたらすはずです。ページを下るにつれて複雑になり、それぞれに独自の利点があります。
まず、関数のベアボーンです。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>";
}