从数组php foreach获取父键

时间:2013-03-21 23:59:45

标签: php arrays

我有一个数组$ arr:

 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>');
    }   

但我得到状态键(字符串'status')作为id值如何获得父$ arr键即(2,23,24)。

4 个答案:

答案 0 :(得分:1)

您应该在foreach中为您的ID指定一个变量:

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>');
}

答案 1 :(得分:0)

通常是这样的:

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

$key应该是您要查找的数字

答案 2 :(得分: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
} 

答案 3 :(得分:0)

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

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

}