【发布时间】:2018-09-17 10:10:18
【问题描述】:
我想格式化我正在使用 simple_html_dom 解析的表格单元格的内容。该表包含没有十进制点的单词、整数或数字以及具有 2 个十进制点的浮点值。我希望它们看起来像这样:
before -> after
"abc" --> "abc" (can stay as they are)
"17" --> "17" (can stay as they are)
"24.24" --> "24.2" (rounded)
"24.29" --> "24.3" (rounded)
我已使用此代码格式化浮点值,但在此示例中整数被格式化为 17.1。我试过!is_integer($td),但没有任何改变。
$table = $html->find('table', 2);
$rowData = array();
// Selected Columns
$columnNumbers = [ 5, 6, 7, 8, 9, 10, 11, 12, 13];
// Loop
foreach($table->find('tr') as $row) {
// initialize array to store the cell data from each row
$flight = array();
foreach($row->find('td') as $columnNumber => $cell) {
// push the cell's text to the array
if ( in_array( $columnNumber, $columnNumbers ) ) {
$flight[] = $cell->plaintext;
}
}
foreach($row->find('th') as $columnNumber => $cell) {
// push the cell's text to the array
if ( in_array( $columnNumber, $columnNumbers ) ) {
$flight[] = $cell->plaintext;
}
}
$rowData[] = $flight;
}
foreach ($rowData as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
if (!is_numeric($td)) {
echo "<td>$td</td>\n";
}
else {
echo "<td>".number_format(floatval ($td), 1)."</td>\n";
}
}
echo '</tr>';
}
【问题讨论】:
标签: php dom html-table numbers format