如何在PHP中读取JSON数组并将其存储在MySQL中

时间:2016-07-21 13:24:51

标签: php mysql arrays json

我是PHP和JSON的新手。我有一个脚本,它从JSON API收集数据并将其存储到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数据是Traits&#34; traits&#34;和专业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

我真的有些可以帮助我。我试着自己找到解决方案,但我看到的解决方案与使用过的代码不符,而且我对这个主题缺乏知识限制了我自己实现它。

2 个答案:

答案 0 :(得分:0)

//Methods to grab information from abhandym_DB database
public void getJSON(View view){
new BackgroundTask().execute();
}

public void parseJSON(View view){
if(JSON_String==null){
    Toast.makeText(getApplicationContext(), "First Get Json", Toast.LENGTH_LONG).show();
}else{
    Intent intent = new Intent(this,Test.class);
    intent.putExtra("JSON_Data",JSON_String);
    startActivity(intent);
}
}

class BackgroundTask extends AsyncTask<Void,Void,String>{

    String json_url;

    @Override
    protected void onPreExecute() {
        json_url = "http://abhandyman.x10host.com/json_get_data.php";
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            InputStream inputSteam = httpURLConnection.getInputStream();
            BufferedReader buffereredReader = new BufferedReader(new InputStreamReader(inputSteam));
            StringBuilder stringBuilder = new StringBuilder();
            while((JSON_String = buffereredReader.readLine())!=null){
            stringBuilder.append(JSON_String+"\n");
            }
            buffereredReader.close();
            inputSteam.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        TextView textView = (TextView)findViewById(R.id.fragment1_textview_JSONAPPEAR);
        textView.setText(result);
        JSON_String = result;
    }
}

答案 1 :(得分:0)

或者,如果您使用的是MySQL 5.7,则只需在数据类型为JSON的表中创建一列,然后将JSON对象或数组写入其中。