1

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

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 岁以下的前五个数组,数组 [31] <-- 这里的前 5 个数组。

我正在尝试的代码是:

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

我不知道为什么 array_slice 不起作用,我做错了什么?

4

2 回答 2

2

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

foreach($products as $key=>$value) {
    $sliced = array_slice($value, 0, 5);
    foreach($sliced as $product) {
        echo $product['name'] . '<br/>';
    }
    echo '<br/>';
}
于 2012-04-20T16:10:54.060 回答
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/>';
}
于 2012-04-20T16:08:01.290 回答