Home > Article > Backend Development > php optimize query foreach
php code optimization
<code>应避免在php foreach里面进行sql查询 以下代码示例使用了laravel的操作数据库api,eloquent orm </code>
Execute two sql queries inside foreach
<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>
Execute one sql query inside foreach
<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>
Move the sql query outside 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>
Summary
<code><span>// 返回数据</span><span>return</span><span>$datas</span>;</code>
<code>经过简单的优化:时间(ms):290 -> 230 -> 180 </code>
ps
<code>postman是一款很好用的chrome调试restful api的插件 </code>
The above introduces PHP optimization query foreach, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.