从数组中返回第一个x项:3

时间:2016-12-30 10:19:36

标签: php php-5.3 php-5.4

假设我有这个数组:

Array
(
[0] => Array
    (
        [id] => 100828698
        [token] => 123
    )

[1] => Array
    (
        [id] => 100828698
        [token] => fdsfsdfsd
    )

[2] => Array
    (
        [id] => 100829014
        [token] => oidshiufjsd
    )

[3] => Array
    (
        [id] => 100829014
        [token] => sdjfdhskjfdsh
    )

)

我尝试这样,但不是那么正确:

$count = count($lastviewedarticles);
if($count>=3)
    array_shift($lastviewedarticles);
    $lastviewedarticles[] = $articleid;
}

你有其他想法吗?

结果应为

1. If count(array) > 3  
2. Make a call of db
3. Fetch first 3 elements
4. Get next 3 elements
etc...

这种情况需要实施

1 个答案:

答案 0 :(得分:0)

使用Array Slice

<?php
 $numberOfItems = 3 // How many items would you like to select?
 $first_items = array_slice(lastviewedarticles, 0, $numberOfItems);
 return $first_items;