Mitchell Bray
Mitchell Bray

Reputation: 558

get parent key from array php foreach

i have an array $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...

i would like to end up with a table row for each element:

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

my current code is:

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

but i am getting the status key (string 'status') as the id value how can i get the parent $arr key ie(2,23,24).

Upvotes: 0

Views: 5013

Answers (4)

Mike Brant
Mike Brant

Reputation: 71414

You should specify a variable for your id in the 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>');
}

Upvotes: 1

tweak2
tweak2

Reputation: 656

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

(spelling)

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
} 

Upvotes: 0

Daniel
Daniel

Reputation: 4946

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

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

}

Upvotes: 0

ITroubs
ITroubs

Reputation: 11215

normally like so:

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

$key should be the numbers you are looking for

Upvotes: 0

Related Questions