首页  >  文章  >  后端开发  >  php 优化查询 foreach

php 优化查询 foreach

WBOY
WBOY原创
2016-08-08 09:24:131278浏览

php代码优化

<code>应避免在php foreach里面进行sql查询
以下代码示例使用了laravel的操作数据库api,eloquent orm
</code>

foreach里面执行两次sql查询

<code><span>// $datas 要返回的数据</span>
foreach (<span>$datas</span> as <span>$_v</span>) {
    <span>// todo 在foreach中查询了两次 **time**: 290 ms(postman)</span><span>$uid</span><span>=</span><span>$_v</span><span>-></span>uid;
    <span>$_v</span><span>-></span>user_name   <span>=</span> User<span>::find</span>(<span>$uid</span>)<span>-></span>username; <span>// 1</span><span>$_v</span><span>-></span>user_avatar <span>=</span> User<span>::find</span>(<span>$uid</span>)<span>-></span>avatar;   <span>// 2</span>
}</code>

foreach里面执行一次sql查询

<code>foreach (<span>$datas</span> as <span>$_v</span>) {
    <span>// todo</span><span>// 简单的优化使得两次sql查询变成一次</span><span>// 在foreach中查询了一次 **time**: 230 ms(postman)</span><span>$user</span><span>=</span> User<span>::find</span>(<span>$_v</span><span>-></span>uid));     <span>// 1</span><span>$_v</span><span>-></span>user_name   <span>=</span><span>$user</span><span>-></span>username;
    <span>$_v</span><span>-></span>user_avatar <span>=</span><span>$user</span><span>-></span>avatar;
}</code>

将sql查询移到foreach外面

<code>上面两个方法都不可避免的在foreach里面执行了数据库查询
**应避免在foreach中执行sql查询**
此处我的做法是再加一层foreach+if来代替sql查询
// 本质上是将foreach中的查询移到外面
</code>
<code><span>// $tmp_data_arr 是存储在foreach外面执行的数据库查询结果</span><span>foreach</span> (<span>$tmp_data_arr</span><span>as</span><span>$value</span>) {
    <span>foreach</span> (<span>$datas</span><span>as</span><span>$_v</span>) {
        <span>if</span> (<span>$_v</span>->uid === <span>$value</span>[<span>'id'</span>]) { <span>// **time**: 180 ms(postman)</span><span>$_v</span>->user_name   = <span>$value</span>[<span>'username'</span>];
            <span>$_v</span>->user_avatar = <span>$value</span>[<span>'avatar'</span>];
        }
    }
}</code>

小结

<code><span>// 返回数据</span><span>return</span><span>$datas</span>;</code>
<code>经过简单的优化:时间(ms):290 -> 230 -> 180
</code>

ps

<code>postman是一款很好用的chrome调试restful api的插件
</code>

以上就介绍了php 优化查询 foreach,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn