Jump to content

foreach and $data[$var][$i] arrays


aliento

Recommended Posts

Hello ,

I have a table like $data[$var][$i] $data is an string, $var is a string and $i is an index int.

I am tired to write for($i=1;,$i<=count($$data[$var],$i++) { echo $data['id'][$i] ... }oouuuff

How i can make it with foreach ?

I tried foreach ($data -> $field as $value) echo $value; but i doesnt work.

Any advise ?

Link to comment
https://forums.phpfreaks.com/topic/249016-foreach-and-datavari-arrays/
Share on other sites

Okay, so there's no key to call on, therefore I'm assuming you want to loop through them all.  What I don't understand is why you would use an array within an array making the inner array the first item of the outer array, which is pointless unless there's multiple arrays in it.

 

A more sensible array would be something like:

 

$data = array(
    'key1' => array(1, 2, 3),
    'key2' => array(1, 2, 3),
    'key3' => array(1, 2, 3)
);

 

Then you could call on it by the key of choice (as it looks like you were trying to do by the previous posts).

 

$data = array(
    'key1' => array(1, 2, 3),
    'key2' => array(4, 5, 6),
    'key3' => array(7, 8, 9)
);

$var = 'key2';

foreach ($data[$var] as $item)
{
    echo "{$item}<br />";
}

 

Outputs

 

4
5
6

 

Hopefully I'm correct on what you're trying to do.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.