【问题标题】:Mysql Results and array manipulationMysql 结果和数组操作
【发布时间】:2011-07-30 02:03:04
【问题描述】:

我被困在一个问题上,希望得到一些指导。我正在使用一个编码糟糕的旧系统,并且没有对用户输入进行任何验证或清理,所以我正在使用的数据库有点失落。

我有一个名为“标签”的列,用于文章的标签。但是每一行都是这样出现的,并且在它们之间有所不同:

标记标记1标记2标记3

标签1、标签2、标签

但我需要将它们组合起来并将它们放入一个数组中,该数组按每个出现的次数列出它们,如下所示:

  • 标签(2)
  • tag1(2)
  • tag2(2)
  • tag3(1)

因为我不是最精通 php,所以我不确定我是否正确地解决了这个问题?

我对在这种规模上操作数组很陌生,这就是我被困在这一点上的原因。您可以在下面查看我正在执行的操作的示例:

  $sql = "SELECT tags, approved FROM articles WHERE approved = '1' ";
  $result = mysql_query($sql);

 while( $rows = mysql_fetch_array($result) ) { 
  $arr = $rows['tags'];
  $arr = str_replace(", ", " ", $arr); // attempting to clean up the data, so that each word appends with a space.
  $arr = str_replace(" ", " ", $arr);

  // Don't know what to do next, or if this is even the right way to do it.

}

感谢任何帮助。

谢谢,莉亚

【问题讨论】:

  • 我想我卡住了,因为脚本为每一行输出一个数组,我不知道如何进行操作,过去一小时的所有尝试都失败了
  • 可以使用explode函数将字符串转换为数组。
  • @FrustratedWithFormsDesigner - 是的,但这不涉及每行数据的格式化方式。它将它放入一个数组中,如:array() { [0] => tag, tag1, tag3, tag4 [1] => tag, tag2, tag6, tag7 }

标签: php mysql arrays


【解决方案1】:

也许这会有所帮助。修改您的代码,使每个查询都有一个$tagArr。如果您需要一个完整的标签数组,它会有点不同,但可以使用以下代码轻松编码。

while( $rows = mysql_fetch_array($result) ) { 
  $arr = $rows['tags'];
  $arr = str_replace(", ", " ", $arr); // attempting to clean up the data, so that each word appends with a space.

  // Don't know what to do next, or if this is even the right way to do it.

  $tagArr = array();
  $current_tags = explode(" ", $arr);
  foreach($current_tags as $tag) {
    if(!array_key_exists($tag, $tagArr)) {
      $tagArr[$tag] = 1;
    } else {
      $tagArr[$tag] = $tagArr[$tag]++;
    }
  }

  // now $tagArr has the tag name as it's key, and the number of occurrences as it's value
  foreach($tagArr as $tag => $occurrences) {
    echo $tag . '(' . $occurrences . ')<br />';
  }
}

【讨论】:

  • 不需要 str_replace space with space 行。
  • @Lea 更新了代码。我刚刚遍历了新的$tagArr 数组并回显了信息。还删除了不需要的str_replace
  • Aaron W. - 我现在明白了。感谢您的帮助:)
猜你喜欢
  • 2017-01-07
  • 2015-10-24
  • 2017-10-03
  • 1970-01-01
  • 2015-09-03
  • 2012-02-29
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多