array_slice - 为什么这在foreach中不起作用

时间:2012-04-20 16:06:05

标签: php

这里的总菜鸟。我有一个看起来像的数组:

Array
(
    [15] => Array
      (
        [0] => Array
            (
                [id] => 5216
                [name] => Grow your own Irish Shamrock gifts set
                [ordered] => 473
                [image] => FunShamrockPot.jpg
            )

        [1] => Array
            (
                [id] => 5217
                [name] => Irish Shamrock Seeds
                [ordered] => 357
                [image] => FunShamrockSeed.jpg
            )

        [2] => Array
            (
                [id] => 5759
                [name] => Ireland Fleece with Shamrock Badge
                [ordered] => 1
                [image] => IrelandFleeceShamrocks.jpg
            )

    )

    [31] => Array
      (
        [0] => Array
            (
                [id] => 5081
                [name] => Tartan Guinness Flat Cap
                [ordered] => 356
                [image] => GuinnessTartanFlatCap.jpg
            )

        [1] => Array
            (
                [id] => 4894
                [name] => Black signature emblem Guinness baseball hat
                [ordered] => 176
                [image] => GuinnessSigBBHat.jpg
            )

该数组被称为$ products,我试图在每个顶部数组中打印出前五个数组(如果有意义的话),换句话说,数组[15]< - 15个以下的前五个数组, array [31]< - 这里的前5个数组。

我正在尝试的代码是:

foreach($products as $key=>$value) {
    array_slice($value, 0, 5);
    foreach($value as $product) {
        echo $product['name'] . '<br/>';
    }
    echo '<br/>';
}

我无法弄清楚为什么array_slice不起作用,我做错了什么?

2 个答案:

答案 0 :(得分:2)

问题是array_slice不修改输入数组,需要返回值:

foreach($products as $key=>$value) {
    $sliced = array_slice($value, 0, 5);
    foreach($sliced as $product) {
        echo $product['name'] . '<br/>';
    }
    echo '<br/>';
}

答案 1 :(得分:0)

foreach($products as $key=>$value) {
    $i = 0;
    foreach($value as $product) {
        if($i <5) {
        echo $product['name'] . '<br/>';
        $i++;
        } else {
        break;
        }
    }
    echo '<br/>';
}

编辑以回答为什么array_slice无法正常工作

你需要做完

$newarray = array_slice($value, 0, 5);
    foreach($newarray as $product) {
    echo $product['name'] . '<br/>';
}