Flatten and Count Uniques in a Multidimensional Array

I know this is super easy for all you PHP nerds out there, but it’s these sorts of posts I enjoy the most. Super simple, short and easy to understand…

Let’s say we have this:

$example = array(
                array("client1", "client2", "client3"),
                array("client1", "client2", "client4"),
                array("client4", "client5", "client6")
            );

We have a multidimensional array of clients. We want to flatten the array and then see how many times each client is duplicated. Here’s a function to do just that:

function flatten_count($multi) {

        $objTmp = (object) array('aFlat' => array());

        array_walk_recursive($multi, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);

        return array_count_values($objTmp->aFlat);

    }

It walks through the array, posting each value to a new array using references and storing them in an object temporary. Then PHP provides us with a handy little function to count all duplicate values in an array and return the values themselves as keys. We run that on the flattened array and return the sorted + counted array.

Easy!

UPDATE: the above code may not work on some setups. I had a problem between PHP 5.2.7 and 5.3.1. If you’re looking for a platform agnostic way:

$values = array();
        $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($example));
        foreach($it as $v) {
            $values[] = $v;
        }

Anyway…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.