开发者

re: whats-the-best-approach-should-i-adopt-for-this-php-problem

this is re: question of question as suggested by Col. Shrapnel to post a new question with clear contents.

I have a facebook user likes data i.e

{
   "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"
      }
      ]}

i want to count the no of each category (e.g here Movie=3, company=2 etc) and save it in mysql table and i also want to save the name of each category in other table(i.e for category Movie there should be Movie(id,name) table and same for all categories). what i have done is


            $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)
        {
开发者_Python百科             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

But it seems inefficient as per speed and consistency concern.

My question is am i using the right approach or there should be something else for this cenario.


This is a cleaner version of the code. I rearranged the json data to create an array sorted by category:

$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;
     }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜