Mike Abineri
Mike Abineri

Reputation: 399

Counting the amount of times a specific key occurs in a multidimensional associative array

I have a multidimensional associative array that I made using the following code:

$column_data = mysqli_fetch_fields($result);
$column_total = json_decode(json_encode($column_data), TRUE);
return $column_total;

The reason is I want to know how many columns are returned from a mysqli query. So I fetched the fields used json e.c.t to turn it into an array hoping that I would find a nice simple way to count the number of times the [name] key occurs.

The I searched two columns email and password in my query and the array looks like the following:

Array
(
    [0] => Array
        (
            [name] => email
            [orgname] => email
            [table] => logins
            [orgtable] => logins
            [def] => 
            [db] => staff_members
            [catalog] => def
            [max_length] => 23
            [length] => 255
            [charsetnr] => 8
            [flags] => 16388
            [type] => 253
            [decimals] => 0
        )

    [1] => Array
        (
            [name] => password
            [orgname] => password
            [table] => logins
            [orgtable] => logins
            [def] => 
            [db] => staff_members
            [catalog] => def
            [max_length] => 60
            [length] => 255
            [charsetnr] => 8
            [flags] => 0
            [type] => 253
            [decimals] => 0
        )

)

And what I am trying to do is count the number of times the [name] key occurs within this array.

If I search one column and use the following code:

$column_count = count(array_keys($result,'Name'));

Then I get the result 1 as expected. However when I search for multiple columns like above this does not work because the $column_data array has multiple indexes.

Is there a way for me to get a the sum total of times the [name] key appears in the $column_total array without having to do a foreach loop?

My desired outcome is I want a function that takes a query result works out how many columns are in the result and returns either:

A. 1 single variable named after the column containing the value like so:

$column_name = $column_value;

B. If multiple columns are selected then just return an associative array using

while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
} 


So yeah how can I can get the sum total of the amount of times [name[ is in the array above?

Upvotes: 0

Views: 52

Answers (1)

Manny Ramirez
Manny Ramirez

Reputation: 148

 function countKeyInArray($key, array $array)
{
    $keys = array();
    foreach ($array as $key => $value) {
        $keys[] = $key;
        if (is_array($array[$key])) {
            $keys = array_merge($keys, array_keys_multi($array[$key]));
        }
    }

    return substr_count(serialize($keys), $key);
}

Upvotes: 1

Related Questions