简体   繁体   English

在两列表格中连续显示php嵌套数组结果

[英]Display php nested array results continuously in two column table

I have a nested array grouping three other arrays: $online, $busy and $offline, in order to display results in this exactly order. 我有一个将三个其他数组分组的嵌套数组:$ online,$ busy和$ offline,以便按此顺序显示结果。

$conteudo = array($online, $ocupado, $offline);

The desired result would be a table in two columns to display results in continuous flow like this: 期望的结果将是一个两列的表格,以显示连续流的结果,如下所示:

online1 | online2
online3 | busy1
busy2   | offline1
offline2| offline3
offline4|

I've been trying lots of foreach loops and playing around changing the html tags, but the closest I can arrive of the desired result is this: 我一直在尝试许多foreach循环并尝试更改html标签,但是我能得到的最接近期望结果的是:

<table width='100%' cellpadding='5' border="1">
<?php
$i = 1; //contador de colunas
$max_colunas = 2; // numero de colunas
foreach ($conteudo as $row) {
    echo "<tr>";
    foreach ($row as $col) {
        foreach ($col as $cell) {
            if ($i == 1) {
                echo "<td>" . $cell . "</td>";
            } elseif ($i == $max_colunas){
                echo "<td>" . $cell . "</td></tr>";
                $i = 0;
            } else {
                echo "<td>" . $cell . "</td>";
            }
            $i++;
        }
    }   
    echo "</tr>"; 
}   

This code will output a table like this: 此代码将输出如下表:

 onine1  | online2 |online3
 busy1   | busy2   |
 offline1|offline2 |offline3|offline4

I can't find out why it ignores completely $max_colunas , seems like it prints all the elements inside the array in row. 我不知道为什么它会完全忽略$max_colunas ,似乎它在行中打印数组中的所有元素。

If I remove lines: 如果我删除行:

 echo "<tr>";
 echo "</tr>";

from beginning and end of foreach it will output all in a row like this: foreach开头和结尾开始,它将连续输出所有内容,如下所示:

onine1  | online2 |online3 | busy1 | busy2 |offline1|offline2 |offline3|offline4

Any suggestions to get the desired output format will be so appreciated. 任何获得所需输出格式的建议将不胜感激。


Edited on 17/01: 于17/01年编辑:

This is how I'm getting the arrays from: 这就是我从中获取数组的方式:

//group people
$online = array(); //group online
$ocupado = array(); //group ocupado
$offline = array(); //group offline

//select people to group
$atendentes = mysql_query("SELECT nome FROM atendentes ORDER BY nome") or die(mysql_error());
$atendentedb = array();

//put selected people in array
while ($row = mysql_fetch_assoc($atendentes)) {
    $atendentedb[] = array('nome' => $row["nome"], 'online' => false);
}


//take people online now and check in selected people
$names = modWhosonlineCustom::getOnlineUserNames();

foreach ($names as $name):
    //foreach ($atendentedb as $atendente):
    for($i = 0; $i < count($atendentedb); $i++):
        $att = strtolower($name->username);

        if ($atendentedb[$i]['nome'] == $att):          
            $atendentedb[$i]['online'] = true;
            break;
        endif;

   endfor;
endforeach;

//check each selected people
foreach ($atendentedb as $atendente) :
    //save temporary data
    $online_ = $atendente['online'];
    $nome_   = $atendente['nome'];  

    //if selected people online
    if ($online_) :
        //take status to show
        $status = mysql_query("SELECT status FROM atendentes WHERE nome = '$nome_' LIMIT 1") or die(mysql_error());
        while ($row = mysql_fetch_assoc($status)):
            $statusdb = $row["status"];
        endwhile;

        //verify and save deppending on status
        switch ($statusdb):

            //if online
            case "disponivel":
                $descricao = mysql_query("SELECT hp_online FROM atendentes WHERE nome = '$nome_' LIMIT 1") or die(mysql_error());
                while ($row = mysql_fetch_assoc($descricao)):
                $online[] = array('info'=>$row['hp_online']);
                endwhile;
                break;

        //if busy
            case "ocupado":
                $descricao = mysql_query("SELECT hp_busy FROM atendentes WHERE nome = '$nome_'  LIMIT 1") or die(mysql_error());
                while ($row = mysql_fetch_assoc($descricao)):
                    $ocupado[] = array('info'=>$row['hp_busy']);
                endwhile;
                break;
        endswitch;

    //if offline
    else:
        $descricao = mysql_query("SELECT hp_offline, horario FROM atendentes WHERE nome = '$nome_' LIMIT 1") or die(mysql_error());
        while ($row = mysql_fetch_assoc($descricao)):
           $offline[] = array('info'=>$row['hp_offline'], 'horario'=>$row['horario']);
        endwhile;

    endif;
endforeach;

EDITED 已编辑

So after following help instructions from DaveRandom I got to this code, which is really a drop away from the right format, except for the "mysterious" behaviour with results coming from array $offline , that are displaying all in "block" (all cells in a row, or all cells in a column) while the other arrays are displaying perfectly(??). 因此,按照DaveRandom的帮助说明进行操作后,我得到了这段代码,它实际上与正确的格式有所不同,除了“神秘的”行为,其结果来自数组$offline ,并在“ block”(所有单元格)中显示所有内容行或一列中的所有单元格),而其他数组则显示完美(??)。

   //group people
   $online = $ocupado = $offline = array();

   //select people to group
   $query = "SELECT nome, status, hp_online, hp_busy, hp_offline, horario
      FROM atendentes
      ORDER BY nome";
  $atendentes = mysql_query($query) or die(mysql_error());
  $atendentedb = array();

  // put selected people in array
  while ($row = mysql_fetch_assoc($atendentes)) {
  $atendentedb[strtolower($row['nome'])] = array_merge($row, array('online' => FALSE));
  }

  //take people online now and check in selected people
  $names = modWhosonlineCustom::getOnlineUserNames();
  foreach ($names as $name) {
  $uname = strtolower($name->username);
  if (isset($atendentedb[$uname])) $atendentedb[$uname]['online'] = TRUE;
  }

  //check each selected people
  foreach ($atendentedb as $name => $atendente) {

  //if selected people online
  if ($atendente['online']) {

 //verify and save deppending on status
 switch ($atendente['status']) {

  //if online
  case 'disponivel':
    $atendentedb[$name]['info'] = $online[] = $atendente['hp_online'];
    break;

  //if busy
  case 'ocupado':
    $atendentedb[$name]['info'] = $ocupado[] = $atendente['hp_busy'];
    break;

  }

  //if offline
  } else {

  $atendentedb[$name]['info'] = $offline[] = $atendente['hp_offline'];
$atendentedb[$name]['info'] = $offline[] = $atendente['horario'];

  }

}

  //*******Display Results
  $conteudo = array_merge($online, $ocupado, $offline);
  $max_colunas = 2; // numero de colunas

  // Start the table
  echo '<table width="100%" cellpadding="5" border="1">'."\n";

  // Loop all the objects
  for ($i = 0, $j = 0; isset($conteudo[$i]); $i++) {
  if ($j == 0) {
  // Output the beginning of a row
  echo "  <tr>\n";
  }
  // Always output a data cell
  echo "    <td>$conteudo[$i]</td>\n";
  if (++$j >= $max_colunas) {
  // Output the end of a row and reset the cell counter
  echo "  </tr>\n";
  $j = 0;
  }
  }

  if ($j) {
  // We may end up with an incomplete row at the end, so pad it with empty cells
  // and close the row
  while ($j++ < $max_colunas) {
 echo "    <td></td>\n";
 }
 echo "  </tr>\n";
 }

 // Close the table
 echo "</table>";

I would say that the first thing to do here is to "flatten" the array - having the multiple dimensions makes this a lot more complicated than it needs to be. 我要说的是,这里要做的第一件事就是“拉平”阵列-具有多个维度会使它比需要的复杂得多。 So rather than creating $conteudo like this: 因此, $conteudo像这样创建$conteudo

$conteudo = array($online, $ocupado, $offline);

...do this instead: ...改为这样做:

$conteudo = array_merge($online, $ocupado, $offline);

Then you can do this: 然后,您可以执行以下操作:

$max_colunas = 2; // numero de colunas

// Start the table
echo '<table width="100%" cellpadding="5" border="1">'."\n";

// Loop all the objects
for ($i = 0, $j = 0; isset($conteudo[$i]); $i++) {
  if ($j == 0) {
    // Output the beginning of a row
    echo "  <tr>\n";
  }
  // Always output a data cell
  echo "    <td>$conteudo[$i]</td>\n";
  if (++$j >= $max_colunas) {
    // Output the end of a row and reset the cell counter
    echo "  </tr>\n";
    $j = 0;
  }
}

if ($j) {
  // We may end up with an incomplete row at the end, so pad it with empty cells
  // and close the row
  while ($j++ < $max_colunas) {
    echo "    <td></td>\n";
  }
  echo "  </tr>\n";
}

// Close the table
echo "</table>";

See it working 看到它正常工作

EDIT 编辑

Try this code for generating your arrays. 尝试使用此代码生成数组。 Note that the structure of your output arrays has been altered to fit my code sample above - if you use this data anywhere else in you script, you will need to modify that code as well. 请注意,已更改输出数组的结构以适合上面的代码示例-如果在脚本的其他任何地方使用此数据,则也需要修改该代码。 I have modified this so that there is only one database query, which would seem to be all that is required. 我已对此进行了修改,以使仅存在一个数据库查询,这似乎就是所需要的。 I have also modified it so that the $atendentedb holds all the user data, including the status and info keys, and all rows contain a horario key. 我还对其进行了修改,以便$atendentedb保存所有用户数据,包括statusinfo键,并且所有行都包含一个horario键。

Because of the fact that your input arrays originally contained more data than the ones created by this code will, the code may need further modification - but try this out and see how you get on. 由于您的输入数组最初包含的数据比此代码创建的数据多,因此可能需要对代码进行进一步的修改-但请尝试一下并看看如何继续。

//group people
$online = $ocupado = $offline = array();

//select people to group
$query = "SELECT nome, status, hp_online, hp_busy, hp_offline, horario
          FROM atendentes
          ORDER BY nome";
$atendentes = mysql_query($query) or die(mysql_error());
$atendentedb = array();

// put selected people in array
while ($row = mysql_fetch_assoc($atendentes)) {
  $atendentedb[strtolower($row['nome'])] = array_merge($row, array('online' => FALSE));
}

//take people online now and check in selected people
$names = modWhosonlineCustom::getOnlineUserNames();
foreach ($names as $name) {
  $uname = strtolower($name->username);
  if (isset($atendentedb[$uname])) $atendentedb[$uname]['online'] = TRUE;
}

//check each selected people
foreach ($atendentedb as $name => $atendente) {

  //if selected people online
  if ($atendente['online']) {

    //verify and save deppending on status
    switch ($atendente['status']) {

      //if online
      case 'disponivel':
        $atendentedb[$name]['info'] = $online[] = $atendente['hp_online'];
        break;

      //if busy
      case 'ocupado':
        $atendentedb[$name]['info'] = $ocupado[] = $atendente['hp_busy'];
        break;

    }

  //if offline
  } else {

    $atendentedb[$name]['info'] = $offline[] = $atendente['hp_offline'].' '.$atendente['horario'];

  }

}

I think you should update counter inside foreach ($col as $cell) { } so it will count elements of the inner arrays and also move decalration of <tr> there. 我认为您应该在foreach ($col as $cell) { }更新counter,这样它将对内部数组的元素进行计数并在其中移动<tr>比例。 if (!is_int($i/2)) { print '<tr><td>' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM