我一直在制作一个组合的社交媒体提要类,它从Facebook获取帖子,并从Twitter发布博客和推文。然后将它们组合成一个列表,以便在网站上显示。问题在于,很难看到任何一种帖子类型,因为twitter比另外两种更活跃。强制一个数组拥有至少一个具有特定值的项目
我设法让它始终显示至少每种类型中的一种,但是我通过计算最终数组中每种类型的数量然后将它们拼接到最后(如果没有)并且想知道是否存在是一个更优雅的解决方案呢?
我的数组包含一堆数组,每个数组都有一个“类型”值,这是我需要测试/至少有一个每个。拼接前
:
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最新的。不过,我希望它有五个最新的,但确保它至少有一个与类型'博客'和一个类型'脸谱'在最后一个数组中。
得到它的工作使用约翰尼·克雷格的想法,下面的代码:
$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++;
}
但真的不知道我喜欢它
向我们展示一些示例代码。 –
@Interstellar_Coder你想要一个例子吗? – ianbarker
给我们一个在拼接前和拼接后输入的样本数组,以便我们可以看到预期的结果。 –