>  기사  >  백엔드 개발  >  循环遍历 组合从数据库里查出来的数据,性能不好,怎么办?

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

WBOY
WBOY원래의
2016-08-04 09:19:02983검색

需求:根据开始、截止时间统计每天的数据
现在的从数据库查出来的数据大概有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) 永远为真

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.