klye_g
klye_g

Reputation: 1242

How to count specific number of a certain key in an object array

I'm completely stumped on this one. I'm trying to figure out how many times I can count the occurrence of a specific key in an object array.

Here is the array:

Array 
(
[0] => stdClass Object
    (
        [id] => 1
        [user_id] => 1
        [group_id] => 1
        [cat_0] => foo
        [cat_1] => bar
        [cat_2] => 
        [cat_3] => 
    )
)

You see that cat_ appears four times but with different numbers on the end of it ranging from 0-3. This number may change and be dynamic, so I need a way to figure out how to return a count of 4, for the 4 keys of "cat_". Any thoughts? Or a good direction to point me in?

Thanks in advance.

Upvotes: 1

Views: 2807

Answers (4)

Affan
Affan

Reputation: 1140

you can use for loop form simple logic .below code work for array and if u want for obj use ->

    $j =1 ;
    for ($i=0;$i<$j;$i++){ //note here we consider that cat_0 is always there and if not then check isset out of for loop cat_0 exist then only go inside loop
          echo 'O/P : '.$val['cat_'$i];
          if (isset($val['cat_'.(int)($i+1)])){
               $j++;
          }
    }

and at last $j contain last value (total). This will work for n no of cat_ .

Upvotes: 0

Aaron W.
Aaron W.

Reputation: 9299

Here's a one-liner option

$catCount = count(preg_grep("/^cat_(\d)+$/", array_keys(get_object_vars($yourObj))));

preg_grep can scan through arrays for a pattern

referenced: https://stackoverflow.com/a/1337711/138383

Upvotes: 1

TheZuck
TheZuck

Reputation: 3621

pseudo-code for simple case:

for all keys:
1. Get the key
2. Apply regex to check if the key matches your prefix
3. if yes ++1 your result

if you need to find duplicates with unknown prefix,meaning you can have the following:

[random-prefix1_1] => v1
[random-prefix1_2] => v2
[random-prefix1_3] => v3
[random-prefix2_1] => v4
[random-prefix2_2] => v5

Then you can do this in reverse, meaning you can search the keys for postfix (_[0-9]+) and remove it and then count identical keys (order alphabetically and find when a key is different from the next one for example)

If both prefix and postfix are unknown, you have a problem :)

Upvotes: 0

deceze
deceze

Reputation: 522066

$count = 0;
foreach ($myObj as $key => $value) {
    if (strpos($key, 'cat_') === 0) {
        $count++;
    }
}

You should really make 'cat' an array with sub-keys, that's a lot easier to work with.

Upvotes: 3

Related Questions