Include ('Inc/common. inc. php '); If (! Isset ($ city) |! Is_array ($ city )){ Exit; } // Print_r ($ city); exit; $ Mem = new Memcache (); $ Mem-> connect ('localhost', '123 '); $ Expires = 15*60; // Check if cache exits If ($ value = $ mem-> get ($ city ))! = FALSE ){ Echo "get key from memcache :"." "; // $ Return = $ mem-> get ($ city ); // Echo json_encode ($ return ); } // If Else { $ ResultJson = fetch_data (); Echo count ($ resultJson )." "; If (count ($ resultJson) = 1 | empty ($ resultJson )){ // Value from mysql Echo "get key from mysql :"." "; $ Query = "select * from pm25 "; $ Result = mysql_query ($ query ); While ($ row = mysql_fetch_assoc ($ result )){ $ Rows [] = $ row; } // Save the obtained value array to memcache For ($ I = 0; $ I $ K [$ I] = $ rows [$ I] ['city']; $ V [$ I] ['city'] = $ rows [$ I] ['city']; $ V [$ I] ['pm25'] = $ rows [$ I] ['pm25']; $ Mem-> set ($ k [$ I], $ v [$ I], false, $ expires ); } // $ Return = $ mem-> get ($ city ); // Echo json_encode ($ return ); } // If Else { Echo "get key from new_writed mysql :"." "; Write_db ($ resultJson ); $ Query = "select * from pm25 "; $ Result = mysql_query ($ query ); While ($ row = mysql_fetch_assoc ($ result )){ $ Rows [] = $ row; } // Write memcache For ($ I = 0; $ I $ K [$ I] = $ rows [$ I] ['city']; $ V [$ I] ['city'] = $ rows [$ I] ['city']; $ V [$ I] ['pm25'] = $ rows [$ I] ['pm25']; $ Mem-> set ($ k [$ I], $ v [$ I], false, $ expires ); } // $ Return = $ mem-> get ($ city ); // Echo json_encode ($ return ); } // Else } // Else Foreach ($ city as $ k => $ v ){ $ Return [$ k] = $ mem-> get ($ v ); } Echo json_encode ($ return ); Function fetch_data (){ $ Url = "http://www.example.com "; // $ Url = ""; $ Data = http_get ($ url ); $ GetJson = json_decode ($ data, true ); Return $ getJson; } // Func fetch_data Function write_db ($ getJson ){ $ SQL = "DELETE FROM pm25 "; Mysql_query ($ SQL ); // Sort the json.txt Foreach ($ getJson as $ key => $ row ){ $ Area [$ key] = $ row ['region']; $ Pm2_5 [$ key] = $ row ['pm2 _ 5']; } Array_multisort ($ area, SORT_ASC, $ pm2_5, SORT_ASC, $ getJson ); For ($ I = 0; $ I If ($ getJson [$ I] ['pm2 _ 5'] = 0) $ Count = 0; Else $ Count = 1; $ Sum = $ getJson [$ I] ['pm2 _ 5']; For ($ j = $ I + 1; $ j If (strcmp ($ getJson [$ j] ['area '], $ getJson [$ I] ['area']) = 0 ){ If ($ getJson [$ j] ['pm2 _ 5'] = 0 ){ Continue; } Else { $ Count ++; $ Sum + = $ getJson [$ j] ['pm2 _ 5']; $ Pm2_5 = $ sum/$ count; } } Else { // Insert into mysql $ Result ['city'] = $ getJson [$ I] ['region']; $ Result ['pm25'] = intval ($ pm2_5 ); $ Query = "insert into pm25 (city, pm25) values ('". $ result ['city']. "',". $ result ['pm25']. ")"; Mysql_query ($ query ); Break; } } } Return $ getJson; } // Func write_db $ Mem-> close (); ?> |