Heim  >  Artikel  >  Backend-Entwicklung  >  循环遍历 组合从数据库里查出来的数据,性能不好,怎么办?

循环遍历 组合从数据库里查出来的数据,性能不好,怎么办?

WBOY
WBOYOriginal
2016-08-04 09:19:02982Durchsuche

需求:根据开始、截止时间统计每天的数据
现在的从数据库查出来的数据大概有10个二维数组,结构相同 如下:

<code>[
    '0' => [
        'time' => '2016-8-3',
        'data1'=> 'xxx',
        ...
    ]
]</code>

因为每个数组中有需要的字段,所以要把这10个二维数组进行组合,思路如下:
根据日期遍历取数据

<code>while (strtotime($start_time)  $v) {
        if (strtotime($start_time) == strtotime($v['time'])) {
            $data[] = $v[];
            ...
        }
    }
    
    foreach($arr as $k => $v) {
        if (strtotime($start_time) == strtotime($v['time'])) {
            $data[] = $v[];
            ...
        }
    }
    
    foreach($arr as $k => $v) {
        if (strtotime($start_time) == strtotime($v['time'])) {
            $data[] = $v[];
            ...
        }
    }
    ...

    $start_time = strtotime($start_time . ' +1 day');
    
}</code>

最后想组合成的数据结构:

<code>[
    '2016-8-3' => [
        'data' => '',
        ...
    ],
    
    '2016-8-4' => [
        'data' => '',
        ...
    ]
    ..
]</code>

可是貌似那个while的性能很不好,跑不出数据,等待好久直接提示:
Maximum execution time of 30 seconds exceeded
各位大神有什么好的建议吗?

回复内容:

需求:根据开始、截止时间统计每天的数据
现在的从数据库查出来的数据大概有10个二维数组,结构相同 如下:

<code>[
    '0' => [
        'time' => '2016-8-3',
        'data1'=> 'xxx',
        ...
    ]
]</code>

因为每个数组中有需要的字段,所以要把这10个二维数组进行组合,思路如下:
根据日期遍历取数据

<code>while (strtotime($start_time)  $v) {
        if (strtotime($start_time) == strtotime($v['time'])) {
            $data[] = $v[];
            ...
        }
    }
    
    foreach($arr as $k => $v) {
        if (strtotime($start_time) == strtotime($v['time'])) {
            $data[] = $v[];
            ...
        }
    }
    
    foreach($arr as $k => $v) {
        if (strtotime($start_time) == strtotime($v['time'])) {
            $data[] = $v[];
            ...
        }
    }
    ...

    $start_time = strtotime($start_time . ' +1 day');
    
}</code>

最后想组合成的数据结构:

<code>[
    '2016-8-3' => [
        'data' => '',
        ...
    ],
    
    '2016-8-4' => [
        'data' => '',
        ...
    ]
    ..
]</code>

可是貌似那个while的性能很不好,跑不出数据,等待好久直接提示:
Maximum execution time of 30 seconds exceeded
各位大神有什么好的建议吗?

你的循环有问题,造成无尽循环了。你去打印下每次循环$start_time和$end_time到底是多少,肯定是strtotime($start_time) 永远为真

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn