小怪兽爱吃肉
如果我正确地解释了代码,您想要查找两种货币的两种产品。这可以在您定义产品和货币后使用嵌套的 foreach 循环来完成。$cacheDirectory = $_SERVER['DOCUMENT_ROOT'] . '/cache/';$url = 'https://remotedomain.com/?get=price';const MAX_CACHE_TIME = 1600;// Optional$output = [];$productList = [ [ 'id' => 10, 'name' => 'SM', ], [ 'id' => 20, 'name' => 'LG', ]];$currencies = [ 'US' => 1, 'EU' => 2,];foreach ($productList as $product) { foreach ($currencies as $currencyName => $currencyId) { $cacheFile = $cacheDirectory . $product['name'] . '_' . $currencyName . '.cache'; if (!file_exists($cacheFile) || filemtime($cacheFile) > MAX_CACHE_TIME) { // No cache or too old $data = file_get_contents($url . '&product=' . $product['id'] . '¤cy=' . $currencyId); $relevantData = substr($data, 17, 2); file_put_contents($cacheFile, $relevantData); // Optional, put the data in an array $output[$product['id']][$currencyId] = $relevantData; } else { $output[$product['id']][$currencyId] = file_get_contents($cacheFile); } }}// Read output with $output[10]['US'] for example分享编辑跟随