Цикл Foreach выполняет только первое значение с возвратом, но возвращает все значения с эхом

Я пытаюсь создать партнерскую таблицу лидеров, используяaffiliwp. Однако я могу получить любое значение, которое хочу, в функции, в которой я использую цикл foreach, который вызывает каждого филиала и отображает «продажи» за месяц.

function affiliate_leaderboard_function() {
global $wpdb;

$getallreferrals = $wpdb->get_results( "SELECT * FROM `wp_affiliate_wp_referrals`");
$getallaffiliates = $wpdb->get_results( "SELECT * FROM `wp_affiliate_wp_affiliates`");
$current_month = get_the_date("m");
$current_year = get_the_date("Y");
$current_date = get_the_date("Y-m-d");
$lastday = date('t',strtotime($current_date));

foreach ($getallaffiliates as $theaffiliate) {
    $user_id = get_userdata( $theaffiliate->user_id );
    $userfirstname = $user_id->first_name;
    $userlastname = $user_id->last_name;
    $totalreferrals = $theaffiliate->referrals;
    $affiliate_id = $theaffiliate->affiliate_id;
    $getaffreferrals = $wpdb->get_results( "SELECT `date` FROM `wp_affiliate_wp_referrals` WHERE `affiliate_id` = $affiliate_id AND `date` >= '$current_year-$current_month-01:00:00:00' AND `date` < '$current_year-$current_month-$lastday:23:59:59' ORDER BY `wp_affiliate_wp_referrals`.`referral_id` ASC");//Get all referrals by affiliate id
    $closerstring = $userfirstname." | This Month's Sales: ".count($getaffreferrals)."<br>";
    if(!empty($getaffreferrals)){
        echo $closerstring;
    }
}
}
add_shortcode('affiliate_leaderboard' , 'affiliate_leaderboard_function');

Поэтому, когда я помещаю шорткод на место и использую «echo $closersstring», он выдает все правильные данные, имя пользователя, за которым следует количество продаж, которые у него были в текущем месяце. НО шорткод выводится вверху содержимого.

Когда я переключаю его на «return $closersstring», он возвращает только одного партнера вместо всех партнеров в цикле foreach. Я понятия не имею, как заставить его отображать все значения, как это делает функция эха, но мне нужно, чтобы он отображался в нужном месте...


person Mario Flawless    schedule 01.06.2018    source источник


Ответы (4)


В forloop, если вы пишете return, цикл завершается при первом запуске. вместо этого, используя переменную, измените свой код на

$return = '';
foreach ($getallaffiliates as $theaffiliate) {
$user_id = get_userdata( $theaffiliate->user_id );
$userfirstname = $user_id->first_name;
$userlastname = $user_id->last_name;
$totalreferrals = $theaffiliate->referrals;
$affiliate_id = $theaffiliate->affiliate_id;
$getaffreferrals = $wpdb->get_results( "SELECT `date` FROM `wp_affiliate_wp_referrals` WHERE `affiliate_id` = $affiliate_id AND `date` >= '$current_year-$current_month-01:00:00:00' AND `date` < '$current_year-$current_month-$lastday:23:59:59' ORDER BY `wp_affiliate_wp_referrals`.`referral_id` ASC");//Get all referrals by affiliate id
$closerstring = $userfirstname." | This Month's Sales: ".count($getaffreferrals)."<br>";
if(!empty($getaffreferrals)){
    $return_array.= $closerstring;
}
}

return $return_array;
person Vamsi Krishna    schedule 01.06.2018

Возврат прерывает выполнение функции.

Вам нужно сохранить вывод в строке и вернуть его в конце, например:

[...]
    $output= '';
    foreach ($getallaffiliates as $theaffiliate) {
        [...]
        if(!empty($getaffreferrals)){
            $output .= $closerstring;
        }
    }
    return $output;
}
person fain182    schedule 01.06.2018

Создайте свою строку после каждого цикла вместо echo, а затем return в конце:

$result = ""; // Create an empty string

foreach ($getallaffiliates as $theaffiliate) {
  $user_id = get_userdata( $theaffiliate->user_id );
  $userfirstname = $user_id->first_name;
  $userlastname = $user_id->last_name;
  $totalreferrals = $theaffiliate->referrals;
  $affiliate_id = $theaffiliate->affiliate_id;
  $getaffreferrals = $wpdb->get_results( "SELECT `date` FROM `wp_affiliate_wp_referrals` WHERE `affiliate_id` = $affiliate_id AND `date` >= '$current_year-$current_month-01:00:00:00' AND `date` < '$current_year-$current_month-$lastday:23:59:59' ORDER BY `wp_affiliate_wp_referrals`.`referral_id` ASC");//Get all referrals by affiliate id
  $closerstring = $userfirstname." | This Month's Sales: ".count($getaffreferrals)."<br>";
  if(!empty($getaffreferrals)){
    $result .= $closerstring; // Add the data
  }
}

return $result; // you return the full string
person Mickaël Leger    schedule 01.06.2018

Добавить строку и вернуться.

    function affiliate_leaderboard_function() {
    global $wpdb;

        $getallreferrals = $wpdb->get_results( "SELECT * FROM `wp_affiliate_wp_referrals`");
        $getallaffiliates = $wpdb->get_results( "SELECT * FROM `wp_affiliate_wp_affiliates`");
        $current_month = get_the_date("m");
        $current_year = get_the_date("Y");
        $current_date = get_the_date("Y-m-d");
        $lastday = date('t',strtotime($current_date));

        $returnstring='';
        foreach ($ge1tallaffiliates as $theaffiliate) {
          $user_id = get_userdata( $theaffiliate->user_id );
          $userfirstname = $user_id->first_name;
          $userlastname = $user_id->last_name;
          $totalreferrals = $theaffiliate->referrals;
          $affiliate_id = $theaffiliate->affiliate_id;
          $getaffreferrals = $wpdb->get_results( "SELECT `date` FROM `wp_affiliate_wp_referrals` WHERE `affiliate_id` = $affiliate_id AND `date` >= '$current_year-$current_month-01:00:00:00' AND `date` < '$current_year-$current_month-$lastday:23:59:59' ORDER BY `wp_affiliate_wp_referrals`.`referral_id` ASC");//Get all referrals by affiliate id
       $closerstring = $userfirstname." | This Month's Sales: ".count($getaffreferrals)."<br>";
        if(!empty($getaffreferrals)){
            $returnstring .=$closerstring;
           }
       }
           return $returnstring;
    }
    add_shortcode('affiliate_leaderboard' , 'affiliate_leaderboard_function');
person dipmala    schedule 01.06.2018