: This article mainly introduces the php optimized query foreach. if you are interested in the PHP Tutorial, refer to it. Php code optimization
Avoid SQL queries in php foreach. the following code example uses laravel's database operation api, eloquent orm
Execute two SQL queries in foreach
// $ Datas data to be returned foreach ($ datas as $ _ v) {// todo queries twice in foreach ** time **: 290 MS (postman) $ uid = $ _ v-> uid; $ _ v-> user_name = User: find ($ uid)-> username; // 1 $ _ v-> user_avatar = User: find ($ uid)-> avatar; // 2}
Execute an SQL query in foreach
Foreach ($ datas as $ _ v) {// todo // simple optimization turns the two SQL queries into one // The foreach queries the same ** time **: 230 MS (postman) $ user = User: find ($ _ v-> uid); // 1 $ _ v-> user_name = $ user-> username; $ _ v-> user_avatar = $ user-> avatar ;}
Move SQL query outside foreach
The preceding two methods inevitably execute database queries in foreach. ** you should avoid executing SQL queries in foreach. ** In this case, I add foreach + if to replace SQL queries. // In essence, the query in foreach is moved out.
// $ Tmp_data_arr is the result of the database query executed outside the foreach ($ tmp_data_arras $ value) {foreach ($ datasas $ _ v) {if ($ _ v-> uid ===$ value ['id']) {// ** time **: 180 MS (postman) $ _ v-> user_name = $ value ['username']; $ _ v-> user_avatar = $ value ['Avatar '] ;}}
Summary
// Return data return $ datas;
After simple optimization: Time (MS): 290-> 230-> 180
Ps
Postman is a useful plug-in for debugging restful APIs in chrome.