Home > Net >  CakePHP - How To Iterate an Array and Compare Array Values With a Variable
CakePHP - How To Iterate an Array and Compare Array Values With a Variable

Time:08-21

I have this array from $Infor = $this->StudentFeeUtil->getPaymentPlanDetails($currentSessionID); pr($Infor)

Array
(
[0] => Array
    (
        [PaymentPlan] => Array
            (
                [id] => 16
                [payment_plan] => 35
                [submission_date] => 2022-11-30
                [intake_id] => 1263
                [session_id] => 1019
            )

    )

[1] => Array
    (
        [PaymentPlan] => Array
            (
                [id] => 15
                [payment_plan] => 35
                [submission_date] => 2022-10-31
                [intake_id] => 1263
                [session_id] => 1019
            )

    )

[2] => Array
    (
        [PaymentPlan] => Array
            (
                [id] => 14
                [payment_plan] => 30
                [submission_date] => 2022-09-30
                [intake_id] => 1263
                [session_id] => 1019
            )

    )
  )

I would like to iterate through this array and compare the submission_date with the current date $now = new DateTime();. If current date, $now is less than or equal to $submission_date and $currentBalance is greater than 0, then do something. Basically, I want something like this:

// Check if student has balance
        if ($now <= $Infor[0]['PaymentPlan']['submission_date'] && $currentBalance > 0) {
            // Do something
            echo " Tell student to pay up balance!";
        } else if ($now <= $Infor[1]['PaymentPlan']['submission_date'] && $currentBalance > 0){
            // Do something 
            echo " Tell student to pay up balance!";
         } else if ($now <= $Infor[2]['PaymentPlan']['submission_date'] && $currentBalance > 0){
            // Do something 
            echo " Tell student to pay up balance!";
  }

How can I achieve this using foreach()? I am using CakePHP-2 and PHP5.6. I am not sure how best I can implement this.

CodePudding user response:

Assuming $now is a date like 2022-08-20 or so, you can use foreach like below where $row is the value of each row(which is an array) and access the submission_date just like the usual array key access.

<?php

foreach($Infor as $row){
    if($currentBalance > 0 && strtotime($now) <= strtotime($row['PaymentPlan']['submission_date'])){
        // Do something
            echo " Tell student to pay up balance!";
    }
}
  • Related