0

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).

1
  • 2
    You nee to do foreach($array as $key => $value) Commented Mar 22, 2013 at 0:01

4 Answers 4

1

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>');
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks i never really got the as $key => $value before i will mark as answered as soon as the site allows me
0

normally like so:

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

$key should be the numbers you are looking for

Comments

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

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

}

Comments

0
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
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.