0

I have an array follow

[0] => Array
 (
    [month] => Oct
    [amount] => 1200.00
 )

and how do i get [amount] by passing [month]

2
  • You have to either iterate over the array and search for the month value or convert your array to month => amount for direct access. Commented Oct 19, 2012 at 8:18
  • Yes, you have to use a loop. The datastructure is unfortunate for that. If you can change it, this would be the best option. Commented Oct 19, 2012 at 8:19

5 Answers 5

6

You don't. Two options:

  1. Loop:

    foreach ($array as $i) {
         if ($i['month'] == 'Oct') {
             echo $i['amount'];
         }
    }
    
  2. Index the data by month:

    $array = array_combine(array_map(function($i) { return $i['month']; }, $array),
                           $array);
    echo $array['Oct']['amount'];
    
Sign up to request clarification or add additional context in comments.

2 Comments

The second option would only work if the month for each entry is unique. You could always create a month => [amount, ...] map, but that's a bit more complex. Just pointing it out :), it should be enough to get the OP started.
Totally correct, obviously I'm working on assumptions here... :)
1
foreach ($arr as $k => $v) {
    if ($v['month'] == $needleMonth) {
        echo $v['amount'] . ' - that`s it';
        break;
    }
}

Comments

0

You have to loop your array and test each time if your wanted month == $arrayElement[$i]['month']

Comments

0
foreach ($arr as $k=>$v) {
    if ($v['month']=='Oct') {
        echo $v['amount'];
    }
}

Comments

0
$selectedMonth = 'Oct';

foreach($yourArray as $child){

    if($child['month'] == $selectedMonth){
        echo $child['amount'];
    }

}

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.