Ash
Ash

Reputation: 27

Get value of an array key=>value based on value of another key=>value?

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){

                 }
         }
     }
}

Upvotes: 0

Views: 687

Answers (3)

Facundo Fasciolo
Facundo Fasciolo

Reputation: 492

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'];
                ...
            }
        }
    }
}

Upvotes: 0

Dave
Dave

Reputation: 888

do it like this instead:

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

Upvotes: 0

Charlotte Dunois
Charlotte Dunois

Reputation: 4680

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']
         }
     }
}

Upvotes: 6

Related Questions