1

I have a multidimensional array to the tune of $doclist['area']['source'][#]['type']

I would like to get a number of all entries of ['type'] = "title" that are not empty.

Is there a simple way of doing it?

While I am at it, is there a way to get a number of all entries of ['type'] = "title" AND ['area'] = "something" that are not empty?

0

3 Answers 3

2

Assuming by 'area' and 'source' you mean arbitrary strings, you could nest a few loops like so:

$num_titles = 0;
foreach ($doclist as $area => $arr1) {
    foreach ($arr1 as $source => $arr2) {
        foreach ($arr2 as $k => $arr3) {
            if (isset($arr3['title']) && strlen(trim($arr3['title'])))
                $num_titles++;
        }
    }
}
print "Titles: {$num_titles}\n";
print "Areas: " . sizeof($doclist) . "\n";
Sign up to request clarification or add additional context in comments.

Comments

1

Here's the function that I wrote based on rfausak's response:

function countdocs($arr,$x="",$y="") {
        if (($x) && ($y)) {
            return count($arr[$x][$y]);
        } else if ($x) {
            $r=0;
            foreach ($arr[$x] as $arr1) {
                $r+=count($arr1);
            }
            return $r;
        } else {
            $r=0;
            foreach ($arr as $arr1) {
                foreach ($arr1 as $arr2) {
                    $r+=count($arr2);
                }
            }
            return $r;
        }
    }

I thought that someone may find it useful.

Comments

0
$ships = array(
    "Passenger ship" =>
        array("Yacht", "Liner", "Ferry"),
    "War ship" =>
        array("Battle-wagon", "Submarine", "Cruiser"),
    "Freight ship" =>
        array("Tank vessel", "Dry-cargo ship", "Container
      cargo ship")
);

function myCount($var, $i = 0){
    $cnt = 0;
    foreach ($var as $v) {
        if (is_array($v) and $i)
            $cnt += myCount($v, 0);
        $cnt++;
    }
    return $cnt;
}
echo myCount($ships, 1);

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.