php – 强制数组至少有一个具有特定值的项目
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 强制数组至少有一个具有特定值的项目,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2185字,纯文字阅读大概需要4分钟。
内容图文
![php – 强制数组至少有一个具有特定值的项目](/upload/InfoBanner/zyjiaocheng/776/a59005be81204ea9b192ac3b79258e67.jpg)
我一直在制作一个综合的社交媒体饲料课程,可以从Facebook获取帖子,博客和推特上的推文.然后它将它们组合成一个列表以在站点上显示.问题是,很少看到任何一种帖子类型,因为Twitter比其他两种更活跃.
我设法让它始终显示每种类型中的至少一种,但是我通过计算最终数组中每种类型的数量然后将它们拼接到最后(如果没有)并且想知道是否有更优雅来做到这一点解决这个问题?
我的数组包含一堆数组,每个数组都有一个’type’值,这是我需要测试的/至少有一个.
在拼接之前:
Array
(
[0] => Array
(
[id] => 131403235838803968
[from] => foo
[sent] => 1320163947
[type] => tweet
[html] => bar
)
[1] => Array
(
[id] => 131403233250914304
[from] => foo
[sent] => 1320163946
[type] => tweet
[html] => bar
)
[2] => Array
(
[id] => 131403232835674113
[from] => foo
[sent] => 1320163946
[type] => tweet
[html] => bar
)
[3] => Array
(
[id] => 131403230910480384
[from] => foo
[sent] => 1320163946
[type] => tweet
[html] => bar
)
[4] => Array
(
[id] => 131403228834299904
[from] => foo
[sent] => 1320163945
[type] => tweet
[html] => bar
)
[5] => Array
(
[type] => facebook
[from] => foo
[html] => bar
[sent] => 1320065996
)
[6] => Array
(
[type] => facebook
[from] => foo
[html] => bar
[sent] => 1319808945
)
[7] => Array
(
[type] => facebook
[from] => foo
[html] => bar
[sent] => 1319789640
)
[8] => Array
(
[type] => facebook
[from] => foo
[html] => bar
[sent] => 1319707799
)
[9] => Array
(
[type] => facebook
[from] => foo
[html] => bar
[sent] => 1319617295
)
[10] => Array
(
[type] => blogger
[from] => foo
[html] => bar
[sent] => 1320157500
)
[11] => Array
(
[type] => blogger
[from] => foo
[html] => bar
[sent] => 1320148260
)
)
之后它将拥有最新的5个.但是我希望它有最新的五个,但要确保它至少有一个类型’blogger’和一个类型’facebook’在最终数组中.
使用Johnny Craig的想法和以下代码完成了它的工作:
$output = array();
$output[] = $tweets[0];
$output[] = $items[0];
$output[] = $posts[0];
$feed = array_merge($tweets, $items, $posts);
$i = 0;
while ($limit > count($output)) {
if (!in_array($feed[$i], $output)) {
$output[] = $feed[$i];
}
$i++;
}
但不是很确定我喜欢它
解决方法:
你可以这样做:
>获取前5个条目
>检查,他们是否只是推特
>如果是,请先从数组中输入type = facebook或blogger
问题是:什么更快?拆分数组或迭代通过一个查找类型.
编辑:
另一种方法是计算你的推文帖子,所以在迭代你所拥有的数组时,例如$twitter = 3然后将匹配参数更改为!= twitter
内容总结
以上是互联网集市为您收集整理的php – 强制数组至少有一个具有特定值的项目全部内容,希望文章能够帮你解决php – 强制数组至少有一个具有特定值的项目所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。