0

I have to keys, 'payment_date' and 'balance'. I have a function that checks 'payment_date' to see if it's <= 'today', and it works but now I don't know how to fetch 'balance' from that:

function getCurrentBalance($myTable){
    $today = new DateTime('now');
    $today = $today->format('Y-m-d');
    foreach($myTable as $row) {
         foreach($row as $key=>$value) {
                 if ($key == "payment_date" && $value <= $today){

                 }
         }
     }
}
2
  • shouldn't it be $row <= $today Commented Sep 12, 2014 at 20:09
  • @TusharGupta: $row is an array... Commented Sep 12, 2014 at 20:17

3 Answers 3

6

You really don't need the second loop, if you already know the keys you need. You can access them directly.

function getCurrentBalance($myTable){
    $today = new DateTime('now');
    $today = $today->format('Y-m-d');
    foreach($myTable as $row) {
         if ($row['payment_date'] <= $today){
             //Do something with $row['balance']
         }
     }
}
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you! I'm just learning about arrays and this makes sense now. I don't know if this is the correct place to ask but my array has many dates so it's possible that <= $today will return multiple results. Is there a way to specify that only the last result be returned? I.e. I have August 1, Sept 1. With the above, both August 1 and Sept 1 are returned. I only want Sept 1.
@Ash Yes, with array_pop() you'll get the last value.
Thank you Charlotte, but will this return the last result up to <= $today?
What do you mean by "last result up to <= $today"? array_pop() will just return the last element (and pops it out of the array) of the specified array, nothing more.
As I said in my first comment, <=$ today can return multiple results but I would just like the one closest to <= $today. I don't think array_pop() is right for this.
|
0

do it like this instead:

foreach($myTable as $row) 
{
    if ($row['payment_date'] <= $today)
    {
        echo $row['balance'];                        
    }
}

Comments

0

I don't understand very well what do you want to do, I think that your answer is:

function getCurrentBalance($myTable){
    $today = new DateTime('now');
    $today = $today->format('Y-m-d');
    foreach($myTable as $row) {
        foreach($row as $key=>$value) {
            if ($key == "payment_date" && $value <= $today){
                $balance = $row['balance'];
                ...
            }
        }
    }
}

Comments

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.