Baadier Sydow
Baadier Sydow

Reputation: 504

Processing associative array and outputting results

Ive got an associative array thats pulled from mysql results and id like to display results from the array. For some reason its just not printing the results. this is a var_dump of the associative array:

array(7) { 
 ["id"]=>  string(3) "143"
 ["url"]=>  string(61) "http://news.bbc.co.uk/sport1/hi/football/eng_prem/9013345.stm"
 ["title"]=>  string(78) "BBC Sport - Football - Sir Alex Ferguson warns Man Utd ahead of Liverpool game"
 ["excerpt"]=>  string(138) "Carelessness must stop - Ferguson: Manchester United boss Sir Alex Ferguson warns his players to cut out the error... http://bbc.in/9tDv0R"
 ["tweet_count"]=> string(3) "183"
 ["created_at"]=> string(10) "2010-09-19" 
 ["media_type"]=> string(4) "news" 
}

and this the code im using to TRY to process it:

while($row=mysql_fetch_assoc($search))
      {

         foreach($row as $key=>$value)
            {
               echo $value["title"]."<br/>";
            }
         }

Upvotes: 1

Views: 831

Answers (3)

Phill Pafford
Phill Pafford

Reputation: 85348

How to get the array values you wanted

while($row=mysql_fetch_assoc($search))
{
  foreach($row as $value)
  {
    echo "Title: ".$value['title']."<br />";
    echo "Excerpt: ".$value['excerpt']."<br />";
    echo "Title w/ Link: <a href=".$value['url'].">".$value['title']."</a><br />";
  }
}

Upvotes: 0

Michał Kluczka
Michał Kluczka

Reputation: 143

With mysql_fetch_assoc you have one complete row in $row variable.

Then you're doing foreach on this variable, where keys are: "id", "url", "title" (and others), and values are corresponding to these keys.

Instead of $value['title'] use $value

while($row=mysql_fetch_assoc($search))
{
  echo $row['id'].': '.$row['title'];
  foreach($row as $key=>$value)
  {
    echo $key.': '.$value."<br/>";
  }
}

Upvotes: 1

Stewie
Stewie

Reputation: 3121

You already have reached farthest end of the array. Try this:

  foreach($row as $key=>$value)
            {
               echo $value."<br/>";
            }

instead of

 foreach($row as $key=>$value)
            {
               echo $value["title"]."<br/>";
            }

Upvotes: 1

Related Questions