为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
肥皂起泡泡 2023-09-22 17:55:57
我需要显示下面的 [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; ?>也许有更好的(紧凑的)方法来做到这一点?
查看完整描述

1 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

dr-spec您可以获取所有子数组中的所有项目,将它们合并到一个数组中,然后获取唯一值:


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

仅出于学习目的,使用当前代码,您可以检查它是否在数组中以消除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;

或者合并它们以消除第二个循环:


 $result = [];

 foreach( $attributes['doctor'] as $doctor ): // Loop through the top array

    $result = array_merge($result, $doctor['dr-spec']);

 endforeach;

 $result = array_unique($result); 


查看完整回答
反对 回复 2023-09-22
  • 1 回答
  • 0 关注
  • 50 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信