1

I need to display values from [dr-spec] array below and filter duplicates:

Array
(
    [0] => Array
        (
            [dr-spec] => Array
                (
                    [0] => Oncology
                )

        )

    [1] => Array
        (
            [dr-spec] => Array
                (
                    [0] => Plastic Surgery
                    [1] => Dental
                )
        )

    [2] => Array
        (
     
            [dr-spec] => Array
                (
                    [0] => Oncology
                    [1] => Plastic Surgery
                )
        )

)

After two days of trials and errors I made this:

<?php 
 foreach( $attributes['doctor'] as $doctor ): // Loop through the top array
   foreach( $doctor['dr-spec'] as $spec ): // Loop through the dr-spec array
    $result[] = $spec; // assign string into a new array
   endforeach;
 endforeach;
 $result = array_unique($result); // filter duplicates inside the array
 foreach( $result as $result ): 
  echo $result // html ommitted 
<?php endforeach; ?>

Maybe there's a better (compact) way of doing it?

Any help appreciated.

1
  • Do you need to keep the array as it is or is a flat array OK? Commented Aug 11, 2020 at 14:32

1 Answer 1

1

You can get all items in the dr-spec of all subarrays, merge them into a single array and then get the unique values:

$result = array_unique(array_merge(...array_column($attributes['doctor'], 'dr-spec')));

Just for learning purposes using your current code, you could check if it's in the array to eliminate the array_unique:

 foreach( $attributes['doctor'] as $doctor ): // Loop through the top array
   foreach( $doctor['dr-spec'] as $spec ): // Loop through the dr-spec array
    if(!in_array($spec, $result)) {
        $result[] = $spec; // assign string into a new array
    }
   endforeach;
 endforeach;

Or merge them to eliminate the second loop:

 $result = [];
 foreach( $attributes['doctor'] as $doctor ): // Loop through the top array
    $result = array_merge($result, $doctor['dr-spec']);
 endforeach;
 $result = array_unique($result); 
Sign up to request clarification or add additional context in comments.

4 Comments

The second version with in_array is probably inefficient. But then again how many specialities does one doctor have? Unless Dr. Nick or Dr. Phil is on the payroll
Yes, that's just for different ways of doing it; pandemic, working from home, bored...
If you want another way of doing it then add array_flip(array_flip($arr)) that is said to be faster than array_unique
@AbraCadaver, thanks for the solution. Didn't think about !in_array - good idea.

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.