0

I have a PHP array that looks like this

Array
(
    [0] => Array
        (
            [events] => Array
                (
                    [0] => Array
                        (
                            [label] => apple
                            [id] => 3
                        )
                        [1] => Array
                        (
                            [label] => onion
                            [id] => 3
                        )
                        [2] => Array
                        (
                            [label] => pear
                            [id] => 2
                        )
                        [3] => Array
                        (
                            [label] => orange
                            [id] => 1
                        )
                        [4] => Array
                        (
                            [label] => grape
                            [id] => 41
                        )
                )
        )
)

I am trying to get a total count of unique IDs, so in the example above I would want to get a count of 4

Do I need to loop through the array or is there a function that can do it more efficiently? Currently it is a small data set but it could grow fairly large.

2 Answers 2

1

You can use array_column to get all the IDs, and array_unique to remove the duplicates, then count that.

count(array_unique(array_column($array[0]['events'][0], 'id')))
Sign up to request clarification or add additional context in comments.

Comments

0

One way or another you'll have to loop through it. I think most efficiently would be

function getUnique($arr){
 $val = array();
  foreach($arr[0]["events"] as $v){
   $val[$v["id"]] = true;
  }
 return count($val);
}

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.