如何解决筛选重复的数组并将其显示为字符串
我需要显示下面[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; ?>
也许有更好的(紧凑)方法?
任何帮助表示赞赏。
解决方法
您可以获取所有子数组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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。