PHP:删除特定元素之前的所有数组元素

时间:2015-11-11 09:17:04

标签: php arrays loops for-loop

您好,我有以下数组:

$days = array(
            1=>"Sunday",
            2=>"Monday",
            3=>"Tuesday",
            4=>"Wednesday",
            5=>"Thursday",
            6=>"Friday",
            7=>"Saturday"
            );

现在我想创建一个循环,自动删除4号之前的所有对象。
我试过这个:

$startIndex = 4;
for($i = 1; $days < $startIndex; $i++)
{
    unset($days[$i]);
}

但它不起作用。

3 个答案:

答案 0 :(得分:3)

将$天更改为$ i,因为$ i是您的指数值。

$days = array(
            1=>"Sunday",
            2=>"Monday",
            3=>"Tuesday",
            4=>"Wednesday",
            5=>"Thursday",
            6=>"Friday",
            7=>"Saturday"
            );


$startIndex = 4;
for($i = 1; $i < $startIndex; $i++)
{
    unset($days[$i]);
}

print_r($days);

答案 1 :(得分:2)

可以使用array_slice()

给出更短的解决方案
$days = array(
            1=>"Sunday",
            2=>"Monday",
            3=>"Tuesday",
            4=>"Wednesday",
            5=>"Thursday",
            6=>"Friday",
            7=>"Saturday"
            );


$startIndex = 4;
$days = array_slice($days, $startIndex-1, NULL, TRUE);

print_r($days);

返回

Array
(
    [4] => Wednesday
    [5] => Thursday
    [6] => Friday
    [7] => Saturday
)

答案 2 :(得分:0)

你的数组

$days = array
(
     1=>"Sunday",
     2=>"Monday",
     3=>"Tuesday",
     4=>"Wednesday",
     5=>"Thursday",
     6=>"Friday",
     7=>"Saturday"
);

循环删除指定索引之前的所有元素。

# Number to stop the unset.
$split_number =4;
# Loop through array

for($a=0;$a<sizeof($days);$a++)
{
    if($a < $split_number)
        # Unset element if condition is true
        unset($days[$a]);
}

print_r($days);

结果

Array
(
    [4] => Wednesday
    [5] => Thursday
    [6] => Friday
    [7] => Saturday
)

如果您希望索引再次从0开始,则可以使用array_values