我正在尝试编写代码以从 Groupon API 检索交易并在 foreach 循环中按类别合并它们,但我无法按文件正确合并它们。
我想通过示例获取每个类别的文件(第一个数组)。如果可能的话,另一个可以将所有文件连接到一个全局 json 文件中。
我的代码有效,但我的 json 文件格式不正确,我得到如下结果:
"Categorie": "jewelry-and-watches"
}][{
"id": "bracelet-bangle-feuille-cristaux-swarovski",
这是无效的,因为我无法正确合并多个页面。所以结果是:
Error: Parse error on line 49475:
...elry-and-watches"}][{ "id": "bracelet-
----------------------^
Expecting 'EOF', '}', ',', ']', got '['
我可以用字符串替换来更正结果,但这是浪费时间,我想有一个很好的代码来理解这个多重 foreachs 的逻辑......
这是我的代码:
<?php
set_time_limit(0);
ini_set('memory_limit', '-1');
$baseurl="https://partner-int-api.groupon.com/deals.json?country_code=FR&tsToken=XXXXXX";
$baseurl_local="https://partner-int-api.groupon.com/division.json?country_code=FR";
$dir = '/var/www/vhosts/XXXXXXXXXX/import/catalogues/Groupon/';
$extension = ".json";
echo "
\n\n ////////////////////////////////////////////////////////
//GROUPON CATALOGUE FRANCE
//////////////////////////////////////////////////////// \n";
echo "
\n\n ////////////////////////////////////////////////////////
// Import des categories Goods
//////////////////////////////////////////////////////// \n";
$categories=array(
"auto-and-home-improvement",
"baby-kids-and-toys",
"electronics",
"entertainment-and-media",
"for-the-home",
"health-and-beauty",
"jewelry-and-watches",
"health-and-beauty",
"mens-clothing-shoes-and-accessories",
"sports-and-outdoors",
"womens-clothing-shoes-and-accessories");
foreach ($categories as $category) {
$url_cata_test="$baseurl&filters=topcategory:goods&filters=category:$category&limit=1";
$jsontest = file_get_contents($url_cata_test);
$arrtest=json_decode($jsontest);
$items=$arrtest->pagination->count;
echo $items;
$pagemax=ceil($items/98)+1;
$pages = range(0,$pagemax);
foreach ($pages as $page) {
$url_cata="$baseurl&filters=topcategory:goods&filters=category:$category&offset=$page&limit=98";
echo "Cat en cours d import: ".$category."\n";
echo "Page en cours d import: ".$page."\n";
echo "URL Cata: $url_cata \n";
$urls = array($url_cata);
foreach ($urls as $url){
echo " \n //////////////////////////////////// \n";
echo "Categorie en cours d import: ".$category."\n";
echo "Nombre de produits: ".$items."\n";
echo "Nombre de pages: ".$pagemax."\n";
echo "Page en cours d import: ".$page."\n";
echo "URL Cata: $url \n";
echo " \n //////////////////////////////////// \n";
$json = file_get_contents($url);
$datas_decode = json_decode($json,TRUE);
$deals = $datas_decode['deals'];
foreach ($deals as $i => &$element) {$element['Categorie'] = $category;};
$deals_encode = json_encode($deals);
$deals_groupe = json_decode($deals_encode,TRUE);
$allDataGoods = array();
$alldeals = array_merge($allDataGoods,$deals_groupe);
$datas_encode = json_encode($alldeals);
file_put_contents($dir.$category.$extension, $datas_encode, FILE_APPEND);
};
};
};
?>