避免多个foreach循环 [英] Avoid multiple foreach loops
问题描述
在WordPress中使用wpdb类查询数据库时,我经常得到对象的数字数组:
When querying the database using wpdb class in WordPress I often get a numerical array of objects:
array(
[0] => stdClass(
comment_ID = 3
comment_post_ID = 19
user_id = 7
)
[1] => stdClass(
comment_ID = 5
comment_post_ID = 19
user_id = 6
)
)
我需要使用user_id
进行第二次查询.要检索user_id
,我使用foreach
循环,例如:
I require to perform a second query using the user_id
. To retrieve the user_id
I use a foreach
loop like:
$user_ids = array();
foreach($array as $object) {
$user_ids[] = $object->user_id;
}
我想知道是否有PHP本机更好的方法来检索user_id
并完全避免foreach?
I want to know whether there is a PHP native better way of retrieving the user_id
and avoid the foreach altogether?
推荐答案
您可以尝试使用 array_map
代替 foreach
:
You may try to use array_map
instead of foreach
:
$user_ids = array_map(function($obj){ return $obj->user_id; }, $array);
注意::由于使用PHP 5.3 ="nofollow">匿名函数.
NOTE: This example requires at least PHP 5.3
, as it was implemented with anonymous functions.
如基准测试所示,原生 foreach
-循环 array_map
快.它是本机语言结构,因此效率更高.如果忽略这一事实,则只有其他循环构造(while
,for
)或array_map
是唯一的方法.
As the benchmark shows, native foreach
-loop is faster than array_map
. It is more efficient, as it is a native language construction. If ignore this fact, other cycle constructions (while
, for
) or array_map
are the only way.
但是,如果您重构查询,而无需进行php处理,那将是更好的选择.有很多功能,例如INNER JOIN
,LEFT JOIN
,子查询,循环和存储过程.可能真的更快.
But it would be really better, if you reconstruct your query, to execute it without php-processing. There are a lot of functionality like INNER JOIN
, LEFT JOIN
, subqueries, loops and stored procedures. It might be really faster.
这篇关于避免多个foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!