我有以下用户名数组:
Array
(
[0] => Sarah
[1] => Leon
[2] => Gary
[3] => Nathan
[4] => Adam
[5] => Lee
[6] => Alex
[7] => Andy
[8] => Terry
)
我想获取特定名称之后的 3 个用户,以及特定名称之前的 3 个用户。例如。名字'Adam'之后的3个用户和名字'Adam'之前的3个用户
有人知道这是如何实现的吗?
最佳答案
使用array_slice()和 array_search()
<?php
$names = [
'Sarah',
'Leon',
'Gary',
'Nathan',
'Adam',
'Lee',
'Alex',
'Andy',
'Terry',
];
$name = "Adam"; //name to be searched
$foundIndex = array_search($name, $names);
if (false !== $foundIndex) {
$beforeNames = array_slice($names, $foundIndex -3 , 3);
$afterNames = array_slice($names, $foundIndex + 1, 3);
var_dump($beforeNames,$afterNames);
} else {
// not found
}
还可以检查范围是否合适
关于php - 获取某个值之前/之后的数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36594763/