生成问题摘要的PHP多维数组

时间:2009-08-16 22:47:46

标签: php data-structures foreach while-loop

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

如何完成以下步骤?

我有following arrays

array1['id']['title']

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

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

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

我想做以下

  1. 第一个循环
    1. array1[$question_id]
    2. 打印标题
    3. 打印来自array2[$question_id][]的所有代码,用于给定的question_id
  2. 第二个循环
    1. 在1.1中为列表中的下一个question_id执行相同操作
    2. 对于列表中的下一个question_id执行与1.2相同的操作 ...
  3. 对列表中的所有$ question_ids继续此操作
  4. 我使用各种方法未能成功完成程序

    1. to create a multidimensional array such that I can iterate though all items in a singe -foreach:merge_unique在这里还不够。其他合并也删除了一个我不想要的列。
    2. to solve the problem with the two given arrays by while and foreach -sentences:我有3次问题的9次迭代,因为我有一个foreach -clause in a while -loop

2 个答案:

答案 0 :(得分: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>";
}

答案 1 :(得分:1)

我确定我在这里遗漏了一些东西,但是......

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