基于键值在PHP中解析数组

问题描述:

Basic php question here. The following SQL code returns an array containing a key called 'date'. All I want to do is parse the 'date' value based on the key name. Any help?

$result = mysql_query("SELECT * FROM `table` WHERE columnName ='value'") or die(mysql_error());
 $data = array();
while ( $row = mysql_fetch_assoc($result) )
{
  $data[] = $row;
}
echo $data->{'date'}

这里有基本的php问题。 以下SQL代码返回一个包含名为“date”的键的数组。 我想要做的就是根据键名解析'date'值。 有什么帮助吗? p>

  $ result = mysql_query(“SELECT * FROM`table` WHERE columnName ='value'”)或die(mysql_error()); 
 $ data =  array(); 
while($ row = mysql_fetch_assoc($ result))
 {
 $ data [] = $ row; 
} 
echo $ data-> {'date'} 
  code>   pre> 
  div>

Ok here you go

With Foreach

foreach($data as $key => $value)
{
   if($key == 'date')
   {
      // do you parsing stuff
   }
}

Without foreach

$parsing_date = $data['date'];

You're using object syntax on an array which you can't do.

 echo $data['date'],

foreach($data as $key => $value)
{
    if ($key == 'date')
    {
        echo "Date Value: '".$value."'";
        // Do your stuffs...
        echo "Date Final Value: '".$value."'";
    } 
}

mysql_fetch_assoc returns an ASSOCiative array. Which means it returns an array with your table name fields as keys. For example if your table has 3 columns 'date', 'name', and 'color'

Then you would access those fields in the following way.

$result = mysql_query("SELECT * FROM `table` WHERE columnName ='value'") or die(mysql_error());
 $data = array();

while ( $row = mysql_fetch_assoc($result) )
{
  echo $row['date']; //Prints the rows date field
  echo $row['name']; //Prints the row name field and so on.
}