PHP:如何从数组中获取范围?

时间:2015-06-12 14:08:33

标签: php arrays

如果我有一个数组,那么,

$numarray = array("abc", "def", "ghi", "jkl", "mno");

如何选择起点和终点之间的值。如果起点是" def"并且终点是" jkl",那么它应该返回" def"," ghi"和" jkl"。起始和结束字符串是动态的,因此它应该匹配,然后返回值的范围。

2 个答案:

答案 0 :(得分:3)

这应该适合你:

从您的阵列中取出array_slice()

<?php

    $numarray = array("abc", "def", "ghi", "jkl", "mno");
    $start = "def";
    $end = "jkl";   
    $startPosition = array_search($start, $numarray);
    $endPosition = array_search($end, $numarray) - $startPosition + 1;

    print_r(array_slice($numarray, $startPosition, $endPosition));

?>

输出:

Array
(
    [0] => def
    [1] => ghi
    [2] => jkl
)

答案 1 :(得分:1)

为了什么目的这么多函数调用。不进行完整的数组传递

$numarray = array("abc", "def", "ghi", "jkl", "mno");
$start = "def";
$end = "jkl";
$out = false;

$new = array ();

foreach($numarray as $item) {
  if ($item == $start) $out = true;
  if ($out) $new[] = $item;
  if ($item == $end) break;
}

print_r($new);