Php 而不是循环100多次来构建阵列
正如我在上一个问题中告诉过你的那样,如果你的脚本有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
-- 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/>';
}
}