爬虫获取汇率后:如何将多个数组合并为单个数组并转为JSON
解决方法
直接调整代码逻辑,将分散的数组合并为一个结构化数组后转换为JSON格式,具体修改如下:
方案一:结构化关联数组(推荐)
这个方案会将每条汇率数据整理为易读的键值对,方便后续使用:
$client = new Client(); $crawler = $client->request('GET', 'https://www.bi.go.id/id/statistik/informasi-kurs/transaksi-bi/default.aspx'); $exchangeRates = []; $crawler->filter('table[class="table table-striped table-no-bordered table-lg"] > tbody > tr')->each(function ($node) use (&$exchangeRates) { // 处理文本,分割多空格分隔的字段 $text = trim($node->text()); $parts = preg_split('/\s+/', $text); // 结构化每条汇率数据 if (count($parts) === 4) { $exchangeRates[] = [ 'currency_code' => $parts[0], 'unit' => $parts[1], 'buy_rate' => str_replace(',', '.', str_replace('.', '', $parts[2])), // 转换为标准数字格式 'sell_rate' => str_replace(',', '.', str_replace('.', '', $parts[3])) ]; } }); // 转换为格式化的JSON $jsonData = json_encode($exchangeRates, JSON_PRETTY_PRINT); echo $jsonData;
关键修改说明:
- 通过
use (&$exchangeRates)让回调函数能操作外部数组,统一收集所有数据 - 用
preg_split('/\s+/', $text)替代原有的explode('\n', ...),适配文本空格分隔的实际格式 - 可选:将印尼格式的数字(如
9.692,41)转换为标准浮点数格式(9692.41),便于后续计算 JSON_PRETTY_PRINT参数让JSON输出更美观易读
示例输出:
[ { "currency_code": "AUD", "unit": "1", "buy_rate": "9692.41", "sell_rate": "9588.34" }, { "currency_code": "BND", "unit": "1", "buy_rate": "10753.75", "sell_rate": "10646.01" } ]
方案二:合并为字符串数组(极简版)
如果只需要将原字符串合并为数组再转JSON,可使用简化版本:
$client = new Client(); $crawler = $client->request('GET', 'https://www.bi.go.id/id/statistik/informasi-kurs/transaksi-bi/default.aspx'); $exchangeRates = []; $crawler->filter('table[class="table table-striped table-no-bordered table-lg"] > tbody > tr')->each(function ($node) use (&$exchangeRates) { $exchangeRates[] = trim($node->text()); }); $jsonData = json_encode($exchangeRates, JSON_PRETTY_PRINT); echo $jsonData;
示例输出:
[ "AUD 1 9.692,41 9.588,34", "BND 1 10.753,75 10.646,01", "CAD 1 11.173,37 11.058,20" ]
内容的提问来源于stack exchange,提问作者Ezha Syafaat
相关产品推荐
相关产品推荐

