从数组中获取元素作为PHP中的字段名称

时间:2014-08-01 19:47:06

标签: php html

我有一个mysql表中的几个字段(宽度,直径等)。而不是逐个从返回的数据中构建字符串

  $rows = $wpdb->last_result; // Wordpress version

  foreach(array_chunk($rows, 5) as $i => $pair)
  {
    $width .= "<tr><td>Width</td>";
    $diameter .= "<tr><td>Diameter</td>";
    foreach($pair as $row) 
    {   
      $width .= "<td>$row->width mm</td>";
      $diameter .= "<td>$row->diameter mm</td>";
    }

    $width .= "</tr>";
    $diameter .= "</tr>";
  }

我可以将厚度,直径,宽度转换为数组,然后像这样循环:

  foreach(array_chunk($rows, 5) as $i => $pair)
  { 
    $measures = array("width"=>"Width","diameter"=>"Diameter","thickness"=>"Thickness","hours"=>"Hours");
    foreach($measures as $measure=>$title)
    {
        $measure .= "<td>$title</td>";
    }  

    foreach($pair as $row) 
    {   
      foreach($measures as $measure=>$title)
      {
        $measure .= "<td>$row->".$measure." mm </td>";
      }      
    }
    foreach($measures as $measure=>$title)
    {
      $measure .= "</tr>";
    }  
  }

但我收到Object of class stdClass could not be converted to string错误,那么可以这样做吗?

1 个答案:

答案 0 :(得分:1)

这是不允许的:

"<td>$row->".$measure." mm </td>";

我认为连接正在弄乱它,试试这样:

"<td>".$row->$measure." mm </td>";

This应该会有所帮助。