脚本宝典收集整理的这篇文章主要介绍了php – 强制数组至少有一个具有特定值的项目,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我设法让它始终显示每种类型中的至少一种,但是我通过计算最终数组中每种类型的数量然后将它们拼接到最后(如果没有)并且想知道是否有更优雅来做到这一点解决这个问题?
我的数组包含一堆数组,每个数组都有一个’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++; }
但不是很确定我喜欢它
以上是脚本宝典为你收集整理的php – 强制数组至少有一个具有特定值的项目全部内容,希望文章能够帮你解决php – 强制数组至少有一个具有特定值的项目所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。