0

这个问题的目的是找到从 PHP 多维数组中打印数据的最佳方法。

您如何完成以下程序?

我有以下数组

array1['id']['title']

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

数组已由函数生成pg_fetch_array。这允许您通过元素的名称或键来引用元素的每个值。

获取问题标题及其标签的过程

我想做以下事情

  1. 第一个循环
    1. 打印标题array1[$question_id]
    2. 打印array2[$question_id][]给定 question_id 的所有标签
  2. 第二循环
    1. question_id对列表中的下一个执行与 1.1 相同的操作
    2. 对列表中的下一个执行与 1.2 相同的操作question_id...
  3. 对列表中的所有 $question_ids 继续此操作

我使用了各种方法未能成功完成该程序

  1. 创建一个多维数组,以便我可以遍历单个 -foreach 中的所有项目: merge_unique 在这里还不够。其他合并也会删除我不想要的一列。
  2. while通过and foreach-sentences解决两个给定数组的问题:我得到 3 个问题的 9 次迭代,因为我在 while 循环中有一个 foreach 子句
4

2 回答 2

1

前言:以下任何示例都应给出预期结果。当您向下浏览页面时,它们会变得更加复杂,并且每个都有自己的好处。

首先,功能的准系统。你遍历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>";
}
于 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 回答