Jump to content

[SOLVED] Simble question about foreach


JeditL

Recommended Posts

Hi, I'm still a newbie to PHP and I got a simple problem that I just can't get solved.

 

I got an associative array and I would like to use (for example print) only particular fields of the array.

For example my array has fields "name", "address" etc. and it holds many names and addresses. I would like to echo all the names from the array but nothing else.

 

I've tried:

 

foreach ($array as $field)

        echo $field['name'];

 

and I've tried aswell:

 

foreach ($array['name'] as $field

        echo $field;

 

but they just won't work. Please help me. I know this is simple problem and I hope you can help me easily. Thanks to anyone replying.

Link to comment
https://forums.phpfreaks.com/topic/165916-solved-simble-question-about-foreach/
Share on other sites

Try this:

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

      if ($key == 'name') {

             echo "$key: $value<br />";
      }

}

 

It may be different depending on the scope of your array however.  If the above doesn't do it then add var_dump($key); and var_dump($value); inside the foreach statement to find out how your array is structured.

I solved my problem. It was mysql associative array so your method didn't work on that. My bad, I didn't tell about that cause I thought it wouldn't matter but it did. I used this:

 

while($row = mysql_fetch_array($result, MYSQL_ASSOC))

    echo $row['name'];

 

I would still like to know how to display the data of $result array with foreach() if it is even possible. Is it?

BTW, you can also use php mysql_fetch_assoc() Versus mysql_fetch_array($result, MYSQL_ASSOC) ... either is fine though.

 

In your example $result would be the resource handle of the query so you couldn't display that.  I'm not sure what your asking.

Hi, thanks for the reply. ;) What I'm trying to solve here is:

 

What if I had multidimensional array like this:

 

$array['row1'][0]=0;

$array['row1'][1]=1;

$array['row1'][2]=2;

$array['row2'][0]=3;

$array['row2'][1]=4;

$array['row2'][2]=5;

 

and I would like to use foreach to display every field of the array. How do I do that using foreach?

 

 

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.