【问题标题】:While loop to build an array instead of looping 100+ timesWhile 循环构建数组而不是循环 100 次以上
【发布时间】:2019-10-15 11:24:18
【问题描述】:
$wp_query = new WP_Query([
    'post_type' => 'office',
    'post_status' => 'any',
    'posts_per_page' => -1,
]);

$offices = [];
if (count($wp_query->posts) > 0) {
    $offices = $wp_query->posts;
}

$keys = [];
foreach ($offices as $office) {
    $keys[] = get_post_meta($office->ID, '_office_id', true);
}

foreach ($records as $record) {
    $record_key = strtoupper(str_replace(' ', '',
        trim($record->location_id) . trim($record->business_unit)));

    if (isset($keys) & !empty($keys)) {
        if (in_array($record_key, $keys)) {
            echo $record_key . ' has a record in WordPress.<br/>';
        } else {
            echo '<b>' . $record_key . ' doesnt have a record in WordPress.</b><br/>';
        }
    }
}

这是我目前使用上述代码得到的,运行良好:

MONTREALFHTOR 在 WordPress 中有记录。
MPLSFHUSA 在 WordPress 中没有记录。
NEWYORKFHUSA 在 WordPress 中有记录。
ORANGECO.FHUSA 在 WordPress 中没有记录。

但上面的代码将遍历所有 $keys 超过 100 次,直到它匹配所有 $record_key - 这是我想要实现的目标:

 -- While loop over offices  
 -- In the loop, for each office, get post meta location ID and business unit and put together as new key  
 -- Loop through the offices one time, and build an array  
 -- Use that array to loop through $records once to match the $record_key and $keys  

【问题讨论】:

    标签: php wordpress foreach


    【解决方案1】:

    正如我在上一个问题中告诉您的那样 - 如果您的脚本在 100 个元素中运行缓慢,您将不会注意到。但仍然要优化你可以这样做:

    $keys = []; foreach ($offices as $office) {
        // Here you add result of `get_post_meta` as a KEY, not a VALUE, 
        // value is irrelevant and can be set to whatever you want, ie 1
        $keys[get_post_meta($office->ID, '_office_id', true)] = 1; 
    }
    
    foreach ($records as $record) {
        $record_key = strtoupper(str_replace(' ', '',
            trim($record->location_id) . trim($record->business_unit)));
    
        // here you check if KEY exists, it is faster then checking if VALUE exists
        if (!empty($keys[$record_key])) {
            echo $record_key . ' has a record in WordPress.<br/>';
        } else {
            echo '<b>' . $record_key . ' doesnt have a record in WordPress.</b><br/>';
        } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 2016-08-05
      • 2011-10-06
      • 1970-01-01
      • 2016-04-24
      • 2015-09-28
      • 2015-01-04
      相关资源
      最近更新 更多