限制PHP中的数组长度

Alf*_*lfo 9 php arrays

是否可以限制数组中的成员数量,例如LIMIT在MySQL中?举例来说,如果我有$arrayx成员,我只想要回他们的第一个50,我该怎么做呢?

我应该使用的组合count()array_slice(),或者是有一个更简单的方法?

com*_*857 25

使用array_slice应该可以解决问题.

array_slice($array, 0, 50); // same as offset 0 limit 50 in sql
Run Code Online (Sandbox Code Playgroud)


Flo*_*ent 6

使用SPL(更好的内存占用):

// Using fixed array
$fixedArray = SplFixedArray::fromArray($array);
$fixedArray->setSize(min(50, count($array));

// Using iterator
$limitIterator = new LimitIterator(new ArrayIterator($array), 0, 50);
Run Code Online (Sandbox Code Playgroud)