Include (' inc/common.inc.php '); if (! isset ($city) | |! Is_array ($city)) { Exit } Print_r ($city); exit; $mem = new Memcache (); $mem, connect (' localhost ', ' 11211 '); $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)) { To take a value from MySQL echo "Get key from MySQL:". " "; $query = "SELECT * from PM25"; $result =mysql_query ($query); while ($row = Mysql_fetch_assoc ($result)) { $rows []= $row; } The array of values to be obtained is stored in memcache for ($i =0; $i<>< p=""> <> $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<>< p=""> <> $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 [' area ']; $PM 2_5[$key]= $row [' pm2_5 ']; } Array_multisort ($area, SORT_ASC, $pm 2_5,sort_asc, $getJson); for ($i =0; $i<>< p=""> <> if ($getJson [$i] [' Pm2_5 ']==0) $count = 0; Else $count = 1; $sum = $getJson [$i] [' pm2_5 ']; for ($j = $i +1; $j<>< p=""> <> if (strcmp ($getJson [$j] [' area '], $getJson [$i] ["area]] ==0) { if ($getJson [$j] [' pm2_5 ']==0) { Continue } else{ $count + +; $sum + = $getJson [$j] [' pm2_5 ']; $PM 2_5= $sum/$count; } } else{ INSERT INTO MySQL $result [' City ']= $getJson [$i] [' area ']; $result [' Pm25 ']=intval ($pm 2_5); $query = "INSERT into PM25 (CITY,PM25) VALUES ('". $result [' City ']. "',". $result [' PM25 ']. ")"; mysql_query ($query); Break } } } return $getJson; }//func write_db $mem-Close (); ?> |