编辑:我找到了一种替代方法:切片()是一种很好的方法。
我有一个名为$mas的数组。取消设置数组的最后7个元素是可以的,但是当我试图取消前3个元素时,我会得到错误:
注意:未定义偏移量:0
下面是我的代码中几行工作的代码:
$ilgis = count($mas);
unset($mas[$ilgis-1], $mas[$ilgis-2], $mas[$ilgis-3], $mas[$ilgis-4], $mas[$ilgis-5], $mas[$ilgis-6], $mas[$ilgis-7]);这个代码不起作用:
...
unset($mas[0], $mas[1], $mas[2]);似乎它们甚至不存在于这个数组中。有什么办法解决吗?
顺便说一句,echo $mas[0];工作得很完美。
var_dump($mas)输出:
array (size=9)
0 => string 'Paris-Orly - Stockholm-Arlanda' (length=30)
1 => string 'Tuesday 25. Mar 2014 21:15 - Terminal: S' (length=41)
2 => string 'Flight DY4314 - LowFare' (length=26)
3 => string 'Stockholm-Arlanda - Copenhagen' (length=30)
4 => string 'Wednesday 26. Mar 2014 07:00 - Terminal: 5' (length=43)
5 => string 'Flight DY4151 - LowFare' (length=26)
6 => string '1 Adult' (length=7)
7 => string '1 Child (2-11)' (length=14)
8 => string '1 Infant' (length=8)发布于 2014-03-24 12:49:43
您可以选择选择所需的值,而不是取消设置不需要的值。为此目的使用array_slice()。与unset()相比,该解决方案的优点是不必指定索引。
$mas = array(
'Paris-Orly - Stockholm-Arlanda',
'Tuesday 25. Mar 2014 21:15 - Terminal: S',
'Flight DY4314 - LowFare',
'Stockholm-Arlanda - Copenhagen',
'Wednesday 26. Mar 2014 07:00 - Terminal: 5',
'Flight DY4151 - LowFare',
'1 Adult',
'1 Child (2-11)',
'1 Infant'
);
$output = array_slice($mas, 3);
print_r($output);输出:
Array
(
[0] => Stockholm-Arlanda - Copenhagen
[1] => Wednesday 26. Mar 2014 07:00 - Terminal: 5
[2] => Flight DY4151 - LowFare
[3] => 1 Adult
[4] => 1 Child (2-11)
[5] => 1 Infant
)发布于 2014-03-24 12:51:35
或者您可以使用array_shift,将第一个元素从数组中移除,在关联数组的情况下,键并不重要:
array_shift($mas) ;
array_shift($mas) ;
array_shift($mas) ;发布于 2014-03-24 12:58:20
使用前3个索引的unset()对我来说很好:
$mas = array(
0 => 'Paris-Orly - Stockholm-Arlanda',
1 => 'Tuesday 25. Mar 2014 21:15 - Terminal: S',
2 => 'Flight DY4314 - LowFare' ,
3 => 'Stockholm-Arlanda - Copenhagen',
4 => 'Wednesday 26. Mar 2014 07:00 - Terminal: 5',
5 => 'Flight DY4151 - LowFare' ,
6 => '1 Adult' ,
7 => '1 Child (2-11)' ,
8 => '1 Infant' );
unset($mas[0], $mas[1], $mas[2]);
var_dump(array_values($mas));但是,它保留了键,因此您可能试图在取消设置后访问索引0。这将引发undefined offset错误,您需要重新索引数组。上面的示例使用array_values()进行同样的操作。
https://stackoverflow.com/questions/22609818
复制相似问题