为什么我的foreach永远需要加载 [英] Why does my foreach take forever to load

查看:113
本文介绍了为什么我的foreach永远需要加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我点击网站上的提交"按钮以按地址过滤结果时,将运行这段代码.但是由于某种原因,页面重新加载需要花费很长时间, 如果有人对我如何优化代码有任何想法,请告诉我.

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.

我在下面添加了2个函数,这些函数应说明它们的优点.

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

谢谢.

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

所有代码:

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

推荐答案

我最终创建了一个cron作业,以从API中获取数据,将结果存储在多个文本文件中,然后从文本文件中获取数据.比多次查询API快得多.

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.

查询地址解析API日常Cron作业设置

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

这篇关于为什么我的foreach永远需要加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆