re:什么是最好的方法 - 我应该采用这个php问题

时间:2011-03-24 11:19:42

标签: php mysql

这是:question的问题 按照Shrapnel上校的建议发布一个内容清晰的新问题。

我有一个Facebook用户喜欢的数据,即

{
   "data": [
      {
         "name": "Joker",
         "category": "Public figure"
      },
      {
         "name": "Rafael Nadal",
         "category": "Athlete"
      },
      {
         "name": "Lassi",
         "category": "Company"
      },
      {
         "name": "Jacinda Barrett",
         "category": "Public figure"
      },
      {
         "name": "cocacola",
         "category": "Company"
      },
      {
         "name": "SWEENEY TODD",
         "category": "Movie"
      },
      {
         "name": "The Notebook",
         "category": "Movie"
      },
      {
         "name": "Unforgiven",
         "category": "Movie"
      }
      ]}

我想计算每个类别的数量(例如,这里是Movie = 3,company = 2等)并将其保存在mysql表中,我也想保存 其他表中每个类别的名称(即类别电影应该有电影(id,name)表,所有类别都相同)。什么 我做的是


            $movie=0;  // also define all variables here(i.e $company, $public figure etc) so that it would be increamented.
       foreach($like['data'] as $jsondata=>$json)
        {
             if($json['category']==='Movie')
        {
        $name_movie=$json['name'];
        $query1="insert into movies(id,name)values('', '" . mysql_real_escape_string($name_movie). "')";
        $result1=mysql_query($query1) or die("error in query".mysql_error());
        $movie++;   // in the last this $movie++ will be inserted in other table
        }
        else
                    if($json['category']==='company')
                        { do the same steps as above}
                 else
                     .
                     .
                     .
                     //similarly for all others categories

但是,就速度和一致性问题而言似乎效率低下
我的问题是我使用了正确的方法,还是应该有其他内容。

1 个答案:

答案 0 :(得分:1)

这是代码的更简洁版本。我重新安排了json数据以创建按类别排序的数组:

$tables = array('movie', 'company'); //etc
$categories = array();
foreach($like['data'] as $jsondata=>$json)
{
    $categories[$json['category']][] = $json['category'];
{

foreach($categories as $key => $category)
{
    if (in_array($key, $tables))
    {

        $i = 0;
        foreach($category as $item)
        {
            $query1="insert into " . $key . "(id,name)values('', '" . mysql_real_escape_string($item['name']). "')";
            $result1=mysql_query($query1) or die("error in query".mysql_error());
            $i++;
        }
        $category_count[$key] = $i;
     }
}