过滤数组中的重复项并将其显示为字符串

我需要显示下面的 [dr-spec] 数组中的值并过滤重复项:


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

                )

        )


)

经过两天的尝试和错误,我做了这个:


<?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; ?>

也许有更好的(紧凑的)方法来做到这一点?


肥皂起泡泡
浏览 51回答 1
1回答

猛跑小猪

dr-spec您可以获取所有子数组中的所有项目,将它们合并到一个数组中,然后获取唯一值:$result = array_unique(array_merge(...array_column($attributes['doctor'], 'dr-spec')));仅出于学习目的,使用当前代码,您可以检查它是否在数组中以消除array_unique:&nbsp;foreach( $attributes['doctor'] as $doctor ): // Loop through the top array&nbsp; &nbsp;foreach( $doctor['dr-spec'] as $spec ): // Loop through the dr-spec array&nbsp; &nbsp; if(!in_array($spec, $result)) {&nbsp; &nbsp; &nbsp; &nbsp; $result[] = $spec; // assign string into a new array&nbsp; &nbsp; }&nbsp; &nbsp;endforeach;&nbsp;endforeach;或者合并它们以消除第二个循环:&nbsp;$result = [];&nbsp;foreach( $attributes['doctor'] as $doctor ): // Loop through the top array&nbsp; &nbsp; $result = array_merge($result, $doctor['dr-spec']);&nbsp;endforeach;&nbsp;$result = array_unique($result);&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP