Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 而不是循环100多次来构建阵列_Php_Wordpress_Foreach - Fatal编程技术网

Php 而不是循环100多次来构建阵列

Php 而不是循环100多次来构建阵列,php,wordpress,foreach,Php,Wordpress,Foreach,正如我在上一个问题中告诉过你的那样,如果你的脚本有100个元素,你不会注意到它是否慢。但仍然要优化,您可以这样做: -- 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 ar

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

 -- 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  
 -- 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  
$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/>';
    } 
}