简体   繁体   中英

Totalling returned values from functions php

I am using this to pull out some facebook data from a CSV

https://github.com/Maatwebsite/Laravel-Excel

public function lifetime_likes_by_gender_and_age_f18_24()
{
    $result = $this->reader->select(array('lifetime_likes_by_gender_and_age_f18_24'))->get();
    return (int)$result->last()->sum();

}

public function lifetime_likes_by_gender_and_age_f25_34()
{
    $result = $this->reader->select(array('lifetime_likes_by_gender_and_age_f25_34'))->get();
    return (int)$result->last()->sum();;
}

public function lifetime_likes_by_female()
{
    return $this->lifetime_likes_by_gender_and_age_f18_24() + $this->lifetime_likes_by_gender_and_age_f25_34();
}

The problem is the first value is returned as 12 the second is 112. So the answer should be 124 but it is returning 136 which suggests it is doubling up the first value.

Any reasons why and how I can fix it? The PHP version is 7.

I'm guessing that the select method introduces a state to the reader, regarding selected columns. So, when you run the 18_24 method you just select that, but then when you run the 25_34 the previous columns were never unselected, so you select them again.

Could you please try instead

public function lifetime_likes_by_gender_and_age_f18_24()
{
    $result = $this->reader->get(array('lifetime_likes_by_gender_and_age_f18_24'));

    return (int)$result->last()->sum();
}

public function lifetime_likes_by_gender_and_age_f25_34()
{
    $result = $this->reader->get(array('lifetime_likes_by_gender_and_age_f25_34'));

    return (int)$result->last()->sum();
}

I will read a bit more of the library source code, but that should be it.

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