0

Suppose I have some value like this

Array
(
    [0] => stdClass Object
        (
            [amount] => 4000.00
            [monthyear] => 2018-02
        )

    [1] => stdClass Object
        (
            [amount] => 5000.00
            [monthyear] => 2018-01
        )
)

I want to generate some value like this

[5000,4000,0,0,0,0,0,0,0,0,0,0]

I used foreach loop and for loop but I can't understand how to do this, it's actually generating a sum of balance report by month.

Is it possible to generate this value via CodeIgniter?

My query for the above output is:

$this->cm->select_sum = "amount";
$this->cm->select = "DATE_FORMAT(date,'%Y-%m') as monthyear";
$this->cm->table_name = "personal_balance";
$this->cm->where = array("DATE_FORMAT(date,'%Y')" => date('Y'));
$this->cm->group_by = "DATE_FORMAT(date,'%m')";
$balance = $this->cm->get();
3
  • 1
    First you need to be able to successfully create a new array [5000, 4000] by iterating over the existing. Then you can use array_pad() to extend the new array with '0's to the desired length. Commented Jan 25, 2018 at 21:47
  • The report will be month based . this is not important to placed the values at the very first . those values can be anywhere . Commented Jan 25, 2018 at 23:27
  • Show us the loops you have tried. Commented Jan 26, 2018 at 0:07

1 Answer 1

1

Something like that do the job I guess.

$monthBalance = [];
foreach($balance as $entry){
    $month = intval(substr($entry['monthyear']),6,7));
    $monthBalance[$month] = $entry;
}
//so there is [1=>obj(), 2=>obj(), 5=>obj] in it


$value = [];
for($m = 1; $m <= 12; $m++) {

    //if the balance month currently exists in the DB results
    if( isset($monthBalance[$m]) ){

       $value[] = $monthBalance[$m]->amount;

    } else {

       $value[] = 0;

    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

this not gonna work, cause if there was 3 value for month 1,2 and 5 the output for this code will be [1,2,5,0,0,0,0,0,0,0,0,0], But i need to get output like this [1,2,0,0,5,0,0,0,0,0,0,0,], Hope You Understand.
Oh, okey, I try to fixe it ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.