Jayelef
Jayelef

Reputation: 135

JSON decode Array and insert in DB

I have some issue with a decoded Json object sended to a php file. I have tried some different format like this

{"2":"{Costo=13, ID=9, Durata_m=25, Descrizione=Servizio 9}","1":"{Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}"}

or this.

[{"Costo":"7.5","ID":"3","Durata_m":"30","Descrizione":"Barba Rasoio"},{"Costo":"4.5","ID":"4","Durata_m":"20","Descrizione":"Barba Macchinetta"}]

In order the first, any suggestions helps me, then i have converted previous string using GSON, however php doesn't decode.

This is my php:

//Receive JSON
 $JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data['servizi'] as $key => $value) 
    { echo "Key: $key; Value: $value<br />\n";
 }

How can I access single elements of array? What I'm doing wrong? Thanks in advance

Upvotes: 0

Views: 936

Answers (2)

azngunit81
azngunit81

Reputation: 1604

your elements of {Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}

are not properly formated as an array element. That is a pure string and not an array value.

This is a json object with 1 element of array:

{
  "1": {
    "Costo": 7,
    "ID": 8,
    "Durata_m": 20
  }
}

The Inside are json objects. Therefore your json string was not properly formated to operate with that logic. What you had was an element of a string. That is the reason why it was a valid json (passing jsonlint) but was not the correct one that you wanted to use.

UPDATE Because this format is fix, I have a non-elegant way:

//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) { 
    //to separate each element
    $newArray = explode(',',$value);
    $newItem = explode('=', $newArray[1]);
    echo "ID". $newItem[1];
}

That would be the dirty way to do it ONLY IF THE PLACEMENT OF DATA IS FIX. (ie the second element of the first explode is always ID.

I will leave it to someone else to make the suggested code better. I would recommend more to ensure that the json you are receive is proper because as I explained, it is incorrectly formated and as an api developer, you want an adaptive way for any given client to use the data efficiently.

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133410

I think you should check the content in this way

//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) { 
    echo "FROM PHP:  " . $value;

    echo "Test : " .$value['ID'];

}

Upvotes: 1

Related Questions