简体   繁体   中英

Avoid multiple foreach loops

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
    )
)

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;
}

I want to know whether there is a PHP native better way of retrieving the user_id and avoid the foreach altogether?

You may try to use array_map instead of foreach :

$user_ids = array_map(function($obj){ return $obj->user_id; }, $array);

NOTE: This example requires at least PHP 5.3 , as it was implemented with anonymous functions .


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.


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM