2012-04-20 75 views
1

總的noob在這裏。我有一個數組,看起來像:array_slice - 這是怎麼來的,這在foreach裏不起作用

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 
      ) 

的數組稱爲$產品,我想,換句話說,只是打印出每個頂陣列中的第一個五年陣列(如果是有道理的),數組[15] < - 前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將無法正常工作,我究竟做錯了什麼?

回答

2

問題是array_slice不修改輸入數組,你需要的返回值:

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

謝謝! array_slice怎麼會不工作? – 2012-04-20 16:11:18

+0

@hugo河馬看到我的編輯 – squarephoenix 2012-04-20 16:14:35

相關問題