2011-03-24 38 views
0


這是re:question 的問題,正如Col Shrapnel建議發佈帶有明確內容的新問題。回覆:whats-the-best-approach-should-i-adopt-for-this-php-problem

我有一個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" 
     } 
     ]} 

我想算沒有每個類別(例如這裏的電影= 3,公司= 2等),並將其保存在MySQL表,我也想在其他表格中保存每個類別的 名稱(即,對於類別Movie,應該有Movie(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 



但似乎效率低下,因爲每速度和一致性問題。

我的問題是我使用正確的方法還是應該有別的東西這個cenario。

回答

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

感謝您的幫助,但HCB你的代碼給我錯誤的結果,你可以使用樣本JSON數據檢查,對其進行解碼,然後'$ ACHO它item'會給你6次單詞'電影',而在數據中只有3次使用類別電影 – 2011-03-24 12:18:25