php – 强制数组至少有一个具有特定值的项目
发布时间:2020-12-13 16:13:53 所属栏目:PHP教程 来源:网络整理
导读:我一直在制作一个综合的社交媒体饲料课程,可以从Facebook获取帖子,博客和推特上的推文.然后它将它们组合成一个列表以在站点上显示.问题是,很少看到任何一种帖子类型,因为Twitter比其他两种更活跃. 我设法让它始终显示每种类型中的至少一种,但是我通过计算最
我一直在制作一个综合的社交媒体饲料课程,可以从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个条目 问题是:什么更快?拆分数组或迭代通过一个查找类型. 编辑:另一种方法是计算你的推文帖子,所以在迭代你所拥有的数组时,例如$twitter = 3然后将匹配参数更改为!= twitter (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |