V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  yuptyy  ›  全部回复第 4 页 / 共 4 页
回复总数  61
1  2  3  4  
2015-03-06 10:11:11 +08:00
回复了 leassy 创建的主题 程序员 一个算法问题,求高手来答
<?php
$arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function get($arr, $which, $num) {
$index = array_search($which, $arr); //所在key
$before = floor(($num - 1) / 2); //前取得数目
$after = ceil(($num - 1) / 2); //后面取得数目
$count = count($arr); //总容量

if($num >= $count) {
return $arr;
}
if($before > $index) {
return array_slice($arr, 0, $num);
}
elseif(($index + $after) >= $count) {
return array_slice($arr, -$num);
}
else
return array_slice($arr, $index - $before, $num);
}

print_r(get($arr1, 6, 5));
1  2  3  4  
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2269 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 10ms · UTC 13:55 · PVG 21:55 · LAX 05:55 · JFK 08:55
Developed with CodeLauncher
♥ Do have faith in what you're doing.