JeditL Posted July 14, 2009 Share Posted July 14, 2009 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. Quote Link to comment Share on other sites More sharing options...
phporcaffeine Posted July 14, 2009 Share Posted July 14, 2009 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. Quote Link to comment Share on other sites More sharing options...
JeditL Posted July 14, 2009 Author Share Posted July 14, 2009 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? Quote Link to comment Share on other sites More sharing options...
phporcaffeine Posted July 14, 2009 Share Posted July 14, 2009 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. Quote Link to comment Share on other sites More sharing options...
JeditL Posted July 15, 2009 Author Share Posted July 15, 2009 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? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.