dongshan8953 2014-08-27 04:56
浏览 68
已采纳

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

I have a code that retrieve the integer values and then totalling them. However, when I attempt to add thousand separator to the extracted value, it will not totalled correctly.

This is the code:

<?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("
", trim($node->nodeValue))[2]))  . '<br/>';
    $total_A += $sub_no;
    echo $sub_no;
    $convert = number_format( $total_A , 0 , '.' , ',' );
}

    echo "Total: $convert";
?>

I tried :

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

and it works for the extracted value but the total will be messed up. How can I correct this? Thanks!

EDIT: I managed to get the correct output for the total: 407,418,309 but I also want the $sub_no to have thousand seperator too when I echo it(not just the total). But when I do it, the total will be displayed wrongly. Output should be like this:
397,893,1 #notice the separator?
184,471,0
729,391,9
etc...
Total: 407,418,309

  • 写回答

2条回答 默认 最新

  • doupang5433 2014-08-27 05:22
    关注

    You can just sum total all of the variables first, then just format them in the end for viewing purposes. The simple logic here is that separate the arithmetic first, then format them after the arithmetic so that no conflict will go into that.

    $total_A = 0;
    foreach ($nodes as $node) {
        $sub_no =  (int) preg_replace("/[^0-9]/", '', trim(explode("
    ", trim($node->nodeValue))[2]));
        $total_A += $sub_no;
        echo number_format($sub_no, 0 , '.' , ',' ) . '<br/>';
    }
    
    echo "Total: ".number_format($total_A, 0 , '.' , ',' );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端