前言:以下任何示例都应给出预期结果。当您向下浏览页面时,它们会变得更加复杂,并且每个都有自己的好处。
首先,功能的准系统。你遍历array1,并打印出标题。然后你从 array2 中获取与我们当前正在查看的具有相同 id 的数组,循环遍历每个值,并打印该值。
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>";
}