为提取的网站数据添加千位分隔符


Adding thousand separator to extracted website data

我有一个代码可以检索整数值,然后求和它们。然而,当我试图将千分隔符添加到提取的值时,它将无法正确合计。

这是代码:

<?php
$ch = curl_init('http://www.alibaba.com/Products');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$html = curl_exec($ch);
$dom = new DOMDocument();
@$dom->loadHTML($html);
$finder = new DOMXPath($dom);
$nodes = $finder->query('//h4[@class="sub-title"]');
$total_A = 0;
foreach ($nodes as $node) {
    $sub_no =  (int) preg_replace("/[^0-9]/", '', trim(explode("'n", trim($node->nodeValue))[2]))  . '<br/>';
    $total_A += $sub_no;
    echo $sub_no;
    $convert = number_format( $total_A , 0 , '.' , ',' );
}
    echo "Total: $convert";
?>

我试过了:

  $sub_no =  number_format(preg_replace("/[^0-9]/", '', trim(explode("'n", trim($node->nodeValue))[2])), 0 , '.' , ',' )  . '<br/>';

它对提取的值有效,但总数会被打乱。我该如何更正?谢谢

编辑:我设法得到了正确的输出总数:407418309,但我也想要$sub_no在我回显时也有一千个分隔符(而不仅仅是总数)。但当我这样做的时候,总数会显示错误。输出应该是这样的:
397893,1#注意到分离器了吗
184471,0
729391,9
等等。
总计:407418309

为什么不将最终输出回显为number_format()

echo "Total: ".number_format($convert, 0 , '.' , ',' );

或者:

$total_A = 0;
foreach ($nodes as $node) {
    $sub_no =  (int) preg_replace("/[^0-9]/", '', trim(explode("'n", trim($node->nodeValue))[2]))  . '<br/>';
    $total_A += $sub_no;
    echo $sub_no;
}
    echo "Total: ".number_format($total_A, 0 , '.' , ',' );

您可以先对所有变量求和,然后为查看目的对它们进行格式化。这里的简单逻辑是,首先将算术分离,然后在算术之后对它们进行格式化,这样就不会发生冲突。

$total_A = 0;
foreach ($nodes as $node) {
    $sub_no =  (int) preg_replace("/[^0-9]/", '', trim(explode("'n", trim($node->nodeValue))[2]));
    $total_A += $sub_no;
    echo number_format($sub_no, 0 , '.' , ',' ) . '<br/>';
}
echo "Total: ".number_format($total_A, 0 , '.' , ',' );