DanielAttard
DanielAttard

Reputation: 3605

Retrieve array items by key value

Somehow, I have managed to create the array below. Now that the array has been created, can someone explain how I can retrieve such information as:

Thanks.

Upvotes: 1

Views: 108

Answers (4)

confucius
confucius

Reputation: 13327

total number of elements

 count($array_name, COUNT_RECURSIVE);

to count the number for a specific key as in your case you can use this , i dont know if there is another better way to do that

    $count = 0;
    $date =date("Y-m-d H:i:s", mktime(0, 0, 0, '11', '22', '2011')); 
    foreach ($array_name as $arr) {
        foreach ($arr as $inner) {
            if (isset($inner[$date])) {
                ++$count;
            }
        }
    }

Upvotes: 2

Jon Newmuis
Jon Newmuis

Reputation: 26492

The total number of elements can be retrieved by iterating through each array and summing their counts. You can do this by saying:

function get_total_elements() {
    $sum = 0;
    foreach ($outer_arr as $inner_arr) {
        foreach ($inner_arr as $date_arr) {
            $sum += count($date_arr);
        }
    }
    return $sum;
}

To get the total number of elements for a given date, you can just modify it slightly to say:

function get_total_elements_for_date($m, $d, $y) {
    date("Y-m-d H:i:s", mktime(0, 0, 0, $m, $d, $y));
    $sum = 0;
    foreach ($outer_arr as $inner_arr) {
        foreach ($inner_arr as $date_arr) {
            if (isset($date_arr[$date])) {
                $sum++;
            }
        }
    }
    return $sum;
}

Then you can invoke the function by saying (for the example of November 18th, 2011): get_total_elements_for_date(11, 18, 2011).

Upvotes: 0

publikz.com
publikz.com

Reputation: 961

Your need calcucate this in cycle, as ex in foreach:

<?
$arr[0][0]["2011-11-18 00:00:00"] = "C";
$arr[0][1]["2011-11-18 00:00:00"] = "I";
$arr[0][2]["2011-11-18 00:00:00"] = "S";
$arr[1][0]["2011-11-22 00:00:00"] = "C";
$arr[1][1]["2011-11-22 00:00:00"] = "S";


// calc all
$tot = 0;
foreach ($arr as $a1)
  foreach ($a1 as $a)
    $tot ++;
echo "Total: $tot\n<br />"; // echo 5


//Find specific time elem
$tot = 0;
$d_ = "2011-11-18 00:00:00";
foreach ($arr as $a1)
  foreach ($a1 as $a2)
    foreach ($a2 as $a3_k=>$a3_v)
      if ( $a3_k == $d_ )
        $tot ++;
echo "Total of $d_: $tot\n<br />"; // echo 5
?>

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

You could do:

foreach($yourArray as $key => $val) {
  echo "Key is:".$key." and value is:".$val."<br />";
}

Upvotes: 1

Related Questions