MySQL的结果与数组操作 [英] Mysql Results and array manipulation

查看:471
本文介绍了MySQL的结果与数组操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我坚持工作的问题,并且将AP preciate一些指导。我与旧系统,这是codeD要命的工作,并没有做任何确认,或用户输入的sanitzing,所以我使用的数据库是有点大小姐。

I am stuck working on a problem, and would appreciate some guidance. I am working with an old system that was coded awfully, and didnt do any validating, or sanitzing of user input, so the database I'm working with is a bit missy.

我有一列名为标签,用于对物品标签的问题。但是的每行的出现这个样子,以及它们之间的不同:

I have issues with one column called "tags", used for tags for articles. But each row appears like this, and varies between them:

标签标记1 TAG2 TAG3

TAG1,TAG2,标记

但我需要将它们结合起来,并把它们放到由多少次,每一个出现,这样会列出他们的数组:

But I need to combine them and put them into an array that lists them by how many times each one occurs, like this:


  • 标签(2)

  • TAG1(2)

  • 标签2(2)

  • TAG3(1)

  • tag(2)
  • tag1(2)
  • tag2(2)
  • tag3(1)

由于我不是最精明的使用PHP,林不知道如果我要对这个问题是否正确?

Because I'm not the most astute with php, Im not sure if I am going about the problem correctly?

进出口新的这种规模的这就是为什么我停留在这一点上操作数组。您可以查看下面的例子我在做什么如下:

Im new to manipulating arrays on this scale which is why I am stuck at this point. You can view the example below of what I am doing below:

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

}

任何帮助是AP preciated。

Any help is appreciated.

谢谢,LEA

推荐答案

也许这将是有益的。修改code到有一个 $ tagArr 对于每个查询。如果你需要的标签的整个阵列这将是一个有点不同,但可以很容易地使用下面的codeD。

Maybe this will be helpful. Modified your code to have a $tagArr for each query. If you need an overall array of tags it would be a bit different, but could easily be coded using the following.

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 />';
  }
}

这篇关于MySQL的结果与数组操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆