简体   繁体   English

根据键值在PHP中解析数组

[英]Parsing Array in PHP based on Key Values

Basic php question here. 基本的PHP问题在这里。 The following SQL code returns an array containing a key called 'date'. 以下SQL代码返回一个包含名为'date'的键的数组。 All I want to do is parse the 'date' value based on the key name. 我要做的就是根据键名解析“ date”值。 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'}

Ok here you go 好,你去

With Foreach 与Foreach

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

Without foreach 没有foreach

$parsing_date = $data['date'];

您在无法使用的数组上使用对象语法。

 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. mysql_fetch_assoc返回一个ASSOCiative数组。 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' 例如,如果您的表有3列“日期”,“名称”和“颜色”

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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM