2013-03-21 106 views
0

我有一個數組$ ARR:得到陣列PHP的foreach父鍵

Array 
(
[2] => Array 
    (
     [status] => 0 
     [item] => Food Processer 
     [catagory] => Appliance 
    ) 

[23] => Array 
    (
     [status] => 1 
     [item] => 12 cup medium muffin tray 
     [catagory] => Kitchenware 
    ) 

[24] => Array 
    (
     [status] => 1 
     [item] => 24 cup mini muffin tray 
     [catagory] => Kitchenware 
    ) etc... 

我想對每個元素的錶行結束:

<tr id="2" class="0"><td>Food Processer</td><td>Appliance</td></tr> 

我當前的代碼是:

foreach ($arr as $a) 
    { 
    echo('<tr id="'.key($a).'" class="'.$a['status'].'">'); 
     echo('<td>'); 
     echo($a['item']); 
     echo('</td>'); 
     echo('<td>'); 
     echo($a['catagory']); 
     echo('</td>'); 

     echo('</tr>'); 
    } 

,但我得到的狀態鍵(字符串「狀態」)作爲id的值我怎樣才能得到父$ ARR鍵即(2,23,24)。

+2

你的東東做的foreach($數組作爲$鍵=> $值) – Daniel 2013-03-22 00:01:23

回答

0

數量應指定爲您的ID在foreach一個變量:

foreach ($arr as $key => $data) { 
    echo('<tr id="'.$key.'" class="'.$data['status'].'">'); 
    echo('<td>'); 
    echo($data['item']); 
    echo('</td>'); 
    echo('<td>'); 
    echo($data['catagory']); 
    echo('</td>'); 
    echo('</tr>'); 
} 
+0

謝謝,我從來沒有真正得到的是$關鍵=> $值之前,我將標記爲儘快回答的網站,讓我 – 2013-03-22 00:05:10

0

通常像這樣:

foreach($array as $key=>$element) {...} 

$key應該是你正在尋找

0
Array 
(
[2] => Array 
    (
     [status] => 0 
     [item] => Food Processor 
     [category] => Appliance 
    ) 
} 

(拼寫)

foreach ($arr as $key=>$a){ 

    // $a['status'] will be 0 
    // $a['item'] will be 'Food Processor' 
    // $a['category'] will be 'Appliance' 
    // $key will be 2 
} 
+0

您在$ key和$ a之間的字符是錯誤的。應該是「=>」。 – Daniel 2013-03-22 00:05:34

+0

正確,我的不好。 – tweak2 2013-03-22 00:09:32

0
foreach ($arr as $key => $value) { 

echo "key: {$key} --- value: {$value}"; 

}