只是想检查我是否在这里做错了什么,因为对于小数据集,函数工作正常,但记录多一点,我得到最大执行时间错误;
function getValue($products, $storeNum, $productKey) {
foreach($products as $row)
{
if((int)$row->name === (int)$storeNum && (int)$row->product_key === (int)$productKey)
{
return $row->value;
}
}
return 0;
}
输入 $products 数组是这样的:
Array
(
[0] => stdClass Object
(
[value] => 0
[name] => 3195
[product_key] => 13
)
)
PS:在另一个循环中调用函数 getvalue(),该循环创建 400(存储为 Y 轴)乘以 50(产品名称 X 轴)的矩阵
最佳答案
听起来您调用了 getValue
函数 20000 次并且每次都迭代(最坏的情况)整个产品数组。
如果您在 $products
的一次迭代中构建矩阵,它应该运行得更快。这是执行此操作的基本方法:
function makeMatrix($stores, $product_names, $products) {
$matrix = [];
// create the matrix from the lists of stores and product names
foreach ($stores as $store) {
foreach ($product_names as $product_name) {
$matrix[$store][$product_name] = 0;
}
}
// fill the matrix with the list of products
foreach ($products as $product) {
$matrix[$product->name][$product->product_key] = $product->value;
}
return $matrix;
}
我认为这应该更快,因为它运行为:
count(stores) * count(product_names) + count(products)
我的理论是,您目前的运行方式如下:
count(stores) * count(product_names) * triangular_number(count(products))
关于php - 循环有什么问题 - 超过 30 秒的最大执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56367019/