简体   繁体   中英

Why does my foreach take forever to load

This piece of code is run when i hit the submit button on my site to filter out results by address. But for some reason it takes forever for the page to reload, if anyone has any ideas how i can optimize my code please let me know.

I added 2 functions below that should explain what they do better.

Thanks in advance.

  $location = !empty($_POST['saddress']) ? $_POST['saddress'] : "NA";

if ($location != "NA")
    $display = true;
$street = explode(',', $location);
$users = get_users('orderby=nicename&role=employer');
global $wpdb;

$location = $_POST['saddress'];

$street = explode(',', $location);
$cat = $_GET['specializingin'];
//$specilty = 'specialties_'. $cat;


$args = array(
    'meta_query' => array(
        array(
            'key' => 'scategory',
            'value' => $_GET['specializingin'],
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'specialties',
            'value' => ($_GET['specialitiesin'] == 'All Specialties' ? '' : $_GET['specialitiesin']),
            'compare' => 'LIKE'
        ),
    ),
);
//p($args);
$search_users = get_users($args);
//p($search_users);
$formattedAddress = prettyAddress($location);

foreach ($search_users as $k => $user):
    if (!empty($street[0])) {
        $db = prettyAddress(get_user_meta($user->ID, 'company_address', true));
        $match = matchAddress($formattedAddress, $db, count($street));
        if ($match == false)
            unset($search_users[$k]);
    }
endforeach;


$search_users = custom_sorting($search_users);

All of code:

<form name="jobfilter" action="" method="post">
<div class="filter-srch">

    <input id="locationjf" name="saddress" placeholder="Type desired location" class="search-text1" value="<?= $location != 'NA' ? $location : '' ?>" type="text">

</div>


<div class="filter-srch">

    <input class="job-filter-btn" value="" type="submit">

</div>

function prettyAddress($address) {
$location = array();
if (empty($address))
    return $location;

$address = str_replace(" ", "+", $address);
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=AIzaSyCR9coRcI1OXCDowXtMYsSNPYAizM8wZD0";
$result = json_decode(file_get_contents($url), true);
if (!isset($result['results'][0]['address_components']))
    return $location;
$components = $result['results'][0]['address_components'];
foreach ($result['results'][0]['address_components'] as $component) {
    switch ($component['types']) {
        case in_array('street_number', $component['types']):
            $location['street_number'] = $component['long_name'];
            break;
        case in_array('route', $component['types']):
            $location['street'] = $component['long_name'];
            break;
        case in_array('sublocality', $component['types']):
            $location['sublocality'] = $component['long_name'];
            break;
        case in_array('locality', $component['types']):
            $location['city'] = $component['long_name'];
            break;
        case in_array('administrative_area_level_2', $component['types']):
            $location['admin_2'] = $component['long_name'];
            break;
        case in_array('administrative_area_level_1', $component['types']):
            $location['state'] = $component['long_name'];
            $location['state_code'] = $component['short_name'];
            break;
        case in_array('postal_code', $component['types']):
            $location['postal_code'] = $component['long_name'];
            break;
        case in_array('country', $component['types']):
            $location['country'] = $component['long_name'];
            $location['country_code'] = $component['short_name'];
            break;
    }
}
return $location;

}

function matchAddress($search, $db, $count = 0) {
    $match = false;
    if (isset($db['country'])) {
        if (strlen($db['country']) > 2) {
            if (stripos($db['country'], $search['country']) !== FALSE)
                $match = TRUE;
            else
                $match = FALSE;
        } else {
            if (stripos($db['country'], $search['country_code']) !== FALSE)
                $match = TRUE;
            else
                $match = FALSE;
        }
    }
    if ($count == 1)
        return $match;
    if (isset($db['state'])) {
        if (strlen($db['state']) > 2) {
            if (stripos($db['state'], $search['state']) !== FALSE)
                $match = TRUE;
            else
                $match = FALSE;
        } else {
            if (stripos($db['state'], $search['state_code']) !== FALSE)
                $match = TRUE;
            else
                $match = FALSE;
        }
    }
    if ($count == 2)
        return $match;
    if (isset($db['city'])) {
        if (stripos($db['city'], $search['city']) !== FALSE)
            $match = TRUE;
        else
            $match = FALSE;
    }
    return $match;
}

I ended up creating a cron job to fetch the data from the API, store the results in multiple text files and then fetch the data from the text files which is much faster than querying the API multiple times.

query geocode api daily cron job setup

add_action('geocode_daily_event', 'geocode_daily');

function geocode_activation() {
    if ( !wp_next_scheduled( 'geocode_daily_event' ) ) {
        wp_schedule_event( current_time( 'timestamp' ), 'twenty_two_hours', 'geocode_daily_event');
    }
}
add_action('wp', 'geocode_activation');
function geocode_daily(){
    $args = array(
        'meta_query' => array(
            array(
                'key' => 'company_address'
            ),
        ),
    );

    //query execution
    $search_companies = get_users($args);

    foreach ($search_companies as $user){
        $address =  get_user_meta($user->ID, 'company_address', true);
        $address = str_replace(" ", "+", $address);

        $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key={YOUR GEOCODE API KEY HERE}";

        $cache_path = get_stylesheet_directory().'/geocode-cache/';
        $filename = $cache_path.md5($url);

        $result  = file_get_contents($url);
        file_put_contents($filename, $result );
    }
}

Function to query the cached files

function prettyAddress($address) {
    $location = array();
    if (empty($address))
        return $location;

    $address = str_replace(" ", "+", $address);
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=AIzaSyCntthdn3101F8RC8RLzv9QxF_tmCvdqNg";

    $cache_path = get_stylesheet_directory().'/geocode-cache/';
    $filename = $cache_path.md5($url);

    // && ( time() - 84600 < filemtime($filename) )
    if( file_exists($filename) ){
        $result = json_decode(file_get_contents($filename), true);

        if (!isset($result['results'][0]['address_components']))
            return $location;
        $components = $result['results'][0]['address_components'];
        foreach ($result['results'][0]['address_components'] as $component) {
            switch ($component['types']) {
                case in_array('street_number', $component['types']):
                    $location['street_number'] = $component['long_name'];
                    break;
                case in_array('route', $component['types']):
                    $location['street'] = $component['long_name'];
                    break;
                case in_array('sublocality', $component['types']):
                    $location['sublocality'] = $component['long_name'];
                    break;
                case in_array('locality', $component['types']):
                    $location['city'] = $component['long_name'];
                    break;
                case in_array('administrative_area_level_2', $component['types']):
                    $location['admin_2'] = $component['long_name'];
                    break;
                case in_array('administrative_area_level_1', $component['types']):
                    $location['state'] = $component['long_name'];
                    $location['state_code'] = $component['short_name'];
                    break;
                case in_array('postal_code', $component['types']):
                    $location['postal_code'] = $component['long_name'];
                    break;
                case in_array('country', $component['types']):
                    $location['country'] = $component['long_name'];
                    $location['country_code'] = $component['short_name'];
                    break;
            }
        }
    }
    else {
        $result  = file_get_contents($url);
        file_put_contents($filename, $result );
        $result  = json_decode($result , true);

        if (!isset($result['results'][0]['address_components']))
            return $location;
        $components = $result['results'][0]['address_components'];
        foreach ($result['results'][0]['address_components'] as $component) {
            switch ($component['types']) {
                case in_array('street_number', $component['types']):
                    $location['street_number'] = $component['long_name'];
                    break;
                case in_array('route', $component['types']):
                    $location['street'] = $component['long_name'];
                    break;
                case in_array('sublocality', $component['types']):
                    $location['sublocality'] = $component['long_name'];
                    break;
                case in_array('locality', $component['types']):
                    $location['city'] = $component['long_name'];
                    break;
                case in_array('administrative_area_level_2', $component['types']):
                    $location['admin_2'] = $component['long_name'];
                    break;
                case in_array('administrative_area_level_1', $component['types']):
                    $location['state'] = $component['long_name'];
                    $location['state_code'] = $component['short_name'];
                    break;
                case in_array('postal_code', $component['types']):
                    $location['postal_code'] = $component['long_name'];
                    break;
                case in_array('country', $component['types']):
                    $location['country'] = $component['long_name'];
                    $location['country_code'] = $component['short_name'];
                    break;
            }
        }
    }
    return $location;
}

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