从数组php中选择一系列x键

时间:2014-05-13 08:49:46

标签: php

如何回显数组$ database中的范围,例如data2到data3?

$database= array ("data1","data2","data3","data4");

在这种情况下,Array_slice将解决我的问题。

$result = array_slice($database, 1, 2);
var_dump($result);

将输出

array (size=2)
0 => string 'data2' (length=5)
1 => string 'data3' (length=5)

4 个答案:

答案 0 :(得分:3)

如果你有你需要的范围array_slice

http://www.php.net/manual/en/function.array-slice.php

在您的方案中:

$database = array("data1","data2","data3","data4");
$result = array_slice($database, 1, 2);
var_dump($result);

如果您不知道范围,可以使用array_search

找到它

http://uk3.php.net/array_search

在您的方案中:

$database = array("data1","data2","data3","data4","data5","data6","data7","data8","data9");
$startKey = "data2";
$endKey = "data6";

$startRange = array_search($startKey, $database);
$endRange = array_search($endKey, $database);
$result = array_slice($database, $startRange, $endRange - $startRange + 1);
var_dump($result);

但是要小心,如果你有多个相同的值,它将使用它在数组中找到的第一个。

w ^

答案 1 :(得分:0)

你可以使用类似的东西:

$database= array ("data1","data2","data3","data4","data5","data6");

$start = 'data2';
$end = 'data4';
$started = false;
foreach ($database as $key=>$data){
    if ($data == $start) {
        $started = true;
    }
    if ($started == true) {
        echo $data;
    }
    if ($data == $end) {
        break;
    }
}

这是指向ideone:http://ideone.com/vxzMMq

的链接

答案 2 :(得分:0)

如果您使用计数器

,该怎么办?
$database= array("data1","data2","data3","data4");
$i=0;

foreach ($database as $key=>$data){
$i++;
if ($i!=1 && $i!=4)
echo $data;

}

它是一种kludge,但它有效:P

答案 3 :(得分:0)

您可以在每个内部使用if条件来检查正确的索引:

$database= array ("data1","data2","data3","data4");
$i=0;
foreach ($database as $key=>$data){
if($i>0 && $i<3)
 {
  echo $data;
 }
 $i++;
}