如何为数组中的最后一项(来自mysql_fetch_array)做一些不同的事情?

时间:2011-11-29 17:55:25

标签: php mysql

我正在努力确保逗号除了最后一项之外的所有项目之外 - 我正在试图弄清楚如何计算变量列表的最后一项。我决定尝试使用count($ variablename)但它似乎不起作用。

我的语法有问题吗?

$servicearray = mysql_query("select serv_id from org_serv_xref where org_id='".$org_id."'");

  $servi = 0;

while ($servicearrayrow = mysql_fetch_array($servicearray)) {
    $servdescarray = mysql_query("select serv_desc from service where serv_id='".$servicearrayrow['serv_id']."'");

while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
    if ($servi < 5 OR $servi < count($servdescarrayrow)) {
   ECHO $servdescarrayrow['serv_desc'].",";
   $servi++;
    }
    else if ($servi == 5 OR $servi == count($servdescarrayrow)) {
        echo $servdescarrayrow['serv_desc'];
        $servi++;
    }
    else {
        $servi = 0;
        break 2;
    }
}
}

3 个答案:

答案 0 :(得分:0)

因为您在$servi开始0。它将始终小于数组的计数。如果你在1启动它,它应该按照你期望的方式工作。

答案 1 :(得分:0)

将您的查询更改为

$servicearray = mysql_query("select GROUP_CONCAT(serv_id) from org_serv_xref where org_id='".$org_id."'");

现在sql为你构建了一个很好的逗号分隔列表:)

答案 2 :(得分:0)

尽我所知,你试图做这样的事情(尽管我可能完全错了):

// Initialise vars
$lastid = '';
$items = array();

// Do the query
$query = "SELECT serv_desc, serv_id
          FROM service
          WHERE serv_id IN (
            SELECT serv_id
            FROM org_serv_xref
            WHERE org_id='".$org_id."'
          )
          ORDER BY serv_id";
$servdescarray = mysql_query($query);

while ($servdescarrayrow = mysql_fetch_assoc($servdescarray)) {
  // We've reached the next ID, echo the result of the last one.
  if ($lastid != $servdescarrayrow['serv_id']) {
    $lastid = $servdescarrayrow['serv_id'];
    if (count($items)) {
      echo implode(',',$items);
      $items = array();
    }
  }
  if (count($items) == 5) { // We don't want more than 5 items
    continue;
  } else  { // Add an item to the results
    $items[$servdescarrayrow['serv_desc']];
  }
}

// Make sure we get the last one
if (count($items)) {
  echo implode(',',$items);
}