2016-07-21 11 views
0

PHPとJSONの初心者です。私は、JSON APIからデータを収集し、それをMySQLデータベースに保存するスクリプトを持っています。PHPでJSON配列を読み込んでMySQLに保存する方法

スクリプトは問題なく動作していますが、特定の配列データを収集する際に問題があります。 これはスクリプトです:私は追加したい

<?php 
$url=""; 
$db_name=" "; 
$db_server=" "; 
$db_user=" "; 
$db_password=""; 
$newline=PHP_EOL; 

$mysqli = new mysqli($db_server,$db_user, $db_password, $db_name); 
if (mysqli_connect_errno()) { 
printf("Connect failed: %s\n", mysqli_connect_error()); 
exit(); 
}else{ 
echo "You are connected to the database ($db_name)" . $newline; 
} 
echo "Initial character set: ". $mysqli->character_set_name(). $newline; 
if (!$mysqli->set_charset("utf8")) { 
echo "Error loading character set utf8: ", $mysqli->error. $newline; 
exit(); 
} else { 
echo "Current character set: ", $mysqli->character_set_name(). $newline; 
} 

$json = file_get_contents($url . '1}'); 
$obj = json_decode(utf8_encode($json)); 
$totalPages=$obj->totalPages; 


//read page 
for($i = 1; $i < $totalPages ; $i++) { 
echo "Read URL " . $url . $i . '}'. $newline; 
$json = file_get_contents($url . $i . '}'); 
$obj = json_decode($json); 

foreach($obj->items as $item){ 
    $id = $item->id; 
    $Name=$item->name; 
    $FirstName = $item->firstName; 
    $LastName = $item->lastName; 

    $attributes = $item->attributes; 
    foreach($attributes as $attribute){ 
     if ($attribute->name=="fut.attribute.DIV"){ 
      $DIV = $attribute->value; 
     } 
     if ($attribute->name=="fut.attribute.POS"){ 
      $POS = $attribute->value; 
     } 
    } 

    $r = $mysqli->query("SELECT id FROM DATABAS WHERE id=". $id); 
    if ($r->num_rows <= 0){ //INSERT 

     $query = "INSERT INTO DATABASE ("; 
     $query.= "`id` , "; 
     $query.= "`Name` , "; 
     $query.= "`FirstName` , "; 
     $query.= "`LastName` , "; 
     $query.= "`DIV` ,"; 
     $query.= "`POS`) VALUES ("; 

     $query.= $id . " , "; 
     $query.= "'" . $Name . "' , "; 
     $query.= "'" . $FirstName . "' , "; 
     $query.= "'" . $LastName . "' , "; 
     $query.= "'" . $DIV. "' , "; 
     $query.= "'" . $POS. "' "; 
     $query.= ");"; 

     $mysqli->query($query); 
     echo "Last Name inserted was: " . $Name . $newline; 

    }else{ //UPDATE 

     $query = "UPDATE database "; 
     $query.= "SET `Name` ='".$Name."' , "; 
     $query.= "`FirstName` ='".$FirstName."' , "; 
     $query.= "`LastName` ='".$LastName."' , "; 
     $query.= "`DIV`='".$DIV."' , "; 
     $query.= "`POS`='".$POS."' "; 
     $query.= "WHERE id=".$id; 

     $mysqli->query($query); 
     echo "Last ID update was: " . $_id . $newline; 

    } 

} 
} 
$mysqli->close(); 


function replace_unicode_escape_sequence($match) { 
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE'); 
} 
function unicode_decode($str) { 
return preg_replace_callback('/\\\\u([0-9af]{4})/i',   'replace_unicode_escape_sequence', $str); 
} 

JSONデータはトレイト「形質」であるとspecialitiesを名物。データは[]と一緒に保存されています。 属性も同様に格納されますが、ポイントする名前は固定されています。 これは部分的なJsonデータです:

,"position":"RW","playStyle":"Basic","playStyleId":null,"height":170,"weight":72,"birthdate":"1987-06-24","age":29,"acceleration":99,"aggression":58,"agility":95,"balance":98,"ballcontrol":99,"foot":"Left","skillMoves":4,"crossing":90,"curve":99,"dribbling":99,"finishing":99,"freekickaccuracy":99,"gkdiving":6,"gkhandling":11,"gkkicking":15,"gkpositioning":14,"gkreflexes":8,"headingaccuracy":99,"interceptions":36,"jumping":82,"longpassing":89,"longshots":97,"marking":21,"penalties":82,"positioning":99,"potential":95,"reactions":95,"shortpassing":99,"shotpower":89,"slidingtackle":35,"sprintspeed":96,"standingtackle":38,"stamina":91,"strength":71,"vision":99,"volleys":94,"weakFoot":4,"traits":["Shooting - Finesse Shot","Dribbler - Speed Dribbler","One Club Player","Ultimate Professional"],"specialities":["Speedster","Dribbler","Distance Shooter","Crosser","FK Specialist","Acrobat","Clinical Finisher","Complete Forward","Poacher"],"atkWorkRate":"Medium","defWorkRate":"Low","playerType":"TEAM OF THE YEAR","attributes":[{"name":"fut.attribute.PAC","value":99,"chemistryBonus":[0]},{"name":"fut.attribute.SHO","value":98,"chemistryBonus":[0]},{"name":"fut.attribute.PAS","value":97,"chemistryBonus":[0]},{"name":"fut.attribute.DRI","value":99,"chemistryBonus":[0]},{"name":"fut.attribute.DEF","value":40,"chemistryBonus":[0]},{"name":"fut.attribute.PHY","value":75,"chemistryBonus":[0]}],"name":"Messi","quality":"gold","color":"toty","isGK":false,"positionFull":"Right 

私は実際にいくつかの助けになることができます。私は自分自身で解決策を見つけようとしますが、私が見た解決策は使用されたコードに対応しておらず、その知識に関する私の知識の欠如は自分でそれを実装することを制限しています。

答えて

0
$arr = json_decode($json_obj,true);//decode object 
foreach($arr as $ar){ 

     $id = $ar["id"]; 
     $name = $ar["name"]; 
     $system_id = $ar["system_id"]; 
     $max_landing_pad_size = $ar["max_landing_pad_size"]; 
     $distance_to_star = $ar["distance_to_star"]; 
     $faction = $ar["faction"]; 
     $government = $ar["government"]; 
     $allegiance = $ar["allegiance"]; 
     $state = $ar["state"]; 
     $type = $ar["type"]; 
     $has_blackmarket = $ar["has_blackmarket"]; 
     $has_commodities = $ar["has_commodities"]; 
     $has_refuel = $ar["has_refuel"]; 
     $has_repair = $ar["has_repair"]; 
     $has_rearm = $ar["has_rearm"]; 
     $has_outfitting = $ar["has_outfitting"]; 
     $has_shipyard = $ar["has_shipyard"]; 

     //insert values into mysql database 
     $sql="INSERT INTO stations (station_id, name, system_id, max_landing_pad_size, distance_to_star, faction, government, allegiance, state, type, has_blackmarket, has_commodities, has_refuel, has_repair, has_rearm, has_outfitting, has_shipyard) 
     VALUES ('$id', '$name', '$system_id', '$max_landing_pad_size', '$distance_to_star', '$faction', '$government', '$allegiance', '$state', '$type', '$has_blackmarket', '$has_commodities', '$has_refuel', '$has_repair', '$has_rearm', '$has_outfitting', '$has_shipyard')"; 

     if(!mysql_query($sql,$con)) //$con is mysql connection object 
     { 
      die('Error : ' . mysql_error()); 
     } 

} 
+0

私の総コードを置き換えて、あなたの例のようにビルドする必要がありますか?このコードを既存のファイルに挿入する必要はありますか?(私自身の値はもちろんです) – Dekidex

0

または、MySQL 5.7を使用している場合は、データ型JSONのテーブルに列があり、JSONオブジェクトまたは配列を書き込むだけです。

+0

Davidさん、ありがとうございます。 MySQL 5.7。それ以外にも、新しいスクリプトを書いて、私には難しいことが起きることはほとんどありません。(多くの助けを借りて) 既存のスクリプトにコードを追加する方法はありませんか? $属性? – Dekidex

関連する問題