Fetching json array in php - php

I have problem with fetching json array that i send with post by android app.
PHP code :
<?php
$properties_json = json_decode($_POST['property'], true);
foreach ($properties_json->properties as $pro_element) {
echo $pro_element->property_id . '<br/>';
echo $pro_element->property_name . '<br/>';
echo $pro_element->property_value . '---------';
}
JSON array that i post :
{
"properties": [
{
"property_id": "654",
"property_name": "Gender",
"property_value": "Male"
},
{
"property_id": "655",
"property_name": "Name",
"property_value": "Amin"
},
{
"property_id": "656",
"property_name": "Mobile",
"property_value": "654-451-456"
}
]
}
Error :
Invalid argument supplied for foreach()
enter image description here

json_decode($_POST['property'], true); return an array. In your code you're using it as an object. Here is the proper way :
<?php
$properties_json = json_decode($_POST['property'], true);
foreach ($properties_json['properties'] as $pro_element) {
echo $pro_element['property_id'] . '<br/>';
echo $pro_element['property_name'] . '<br/>';
echo $pro_element['property_value'] . '---------';
}
EDIT:
You can check if $_POST['property'] exist and is not null.
<?php
if(isset($_POST['property'])){
if($_POST['property'] != null and $_POST['property'] != ""){
$properties_json = json_decode($_POST['property'], true);
foreach ($properties_json['properties'] as $pro_element) {
echo $pro_element['property_id'] . '<br/>';
echo $pro_element['property_name'] . '<br/>';
echo $pro_element['property_value'] . '---------';
}
}else{
echo "POST['property'] is empty";
}
}else{
echo "Missing POST['property']";
}

You reference $properties_json->properties as if it were an object, but you converted your JSON to an array by doing json_decode($_POST['property'], true); (see the documentation of json_decode)
You either need to change the true to false or do
foreach ($properties_json['properties'] as $pro_element) {

Related

How can I extract specific JSON elements with PHP?

I'm toying with a small program that can pass a list of words to the Merriam-Webster API, and gets returned the definition, part of speech, sample sentence and so on.
The JSON string returned for each word by the API is as follows:
{
"meta": {
"id": "vase",
"uuid": "eb4f8388-84b2-4fd4-bfc8-2686a0222b73",
"src": "learners",
"section": "alpha",
"target": {
"tuuid": "60e7797e-fd75-43e1-a941-3def0963d822",
"tsrc": "collegiate"
},
"stems": [
"vase",
"vaselike",
"vases"
],
"app-shortdef": {
"hw": "vase",
"fl": "noun",
"def": ["{bc} a container that is used for holding flowers or for decoration"]
},
"offensive": false
},
"hwi": {
"hw": "vase",
"prs": [
{
"ipa": "ˈveɪs",
"pun": ",",
"sound": {"audio": "vase0002"}
},
{
"l": "British",
"ipa": "ˈvɑːz",
"sound": {"audio": "vase0003"}
}
]
},
"fl": "noun",
"ins": [
{
"il": "plural",
"if": "vas*es"
}
],
"gram": "count",
"def": [
{
"sseq": [
[
[
"sense",
{
"dt": [
[
"text",
"{bc}a container that is used for holding flowers or for decoration "
],
[
"vis",
[
{"t": "a beautiful Chinese {it}vase{/it}"},
{"t": "a {it}vase{/it} of roses"}
]
]
]
}
]
]
]
}
],
"shortdef": ["a container that is used for holding flowers or for decoration"]
}
]
The code I'm using to pull the information from the API is as follows:
<?php
$handle = fopen("inputfile.txt", "r");
if ($handle)
{
while (($line = fgets($handle)) !== false)
{
// process the line read.
//$json_new = grab_json_definition(trim($line), "collegiate", "0f3ee238-c219-472d-9079-df5ec8c0eb7d");
$json_new = grab_json_definition(trim($line) , "learners", "d300a82d-1f00-4f09-ac62-7ab37be796e8");
$data = json_decode($json_new, true);
echo "Word: " . $data[0]['meta']['id'] . "<br/>";
echo "IPA: " . $data[0]['hwi']['prs'][0][ipa] . "<br/>";
echo "Part of Speech: " . $data[0]['fl'] . "<br/>";
echo "Definition: " . $data[0]['shortdef'][0] . "<br/>";
echo "Sentence: " . $data[0]['def'][0]['sseq'][0][0][0] . "<br/>";
}
fclose($handle);
}
else
{
// error opening the file.
}
function grab_json_definition($word, $ref, $key)
{
$uri = "https://www.dictionaryapi.com/api/v3/references/" . urlencode($ref) . "/json/" . urlencode($word) . "?key=" . urlencode($key);
return file_get_contents($uri);
};
?>
I can easily navigate through to get the Word, Definition and so on, but I can't navigate down to "t" to get the sample sentences. I'm sure it's something basic but I can't figure it out. Any help would be appreciated.
First, your JSON example is broken, I believe it is missing a [ in the beginning.
Now, Here is an example, where I load the contents of the file, json_decode your SINGLE example. Note that I am not adding a foreach loop or while loop, but I am getting all of the attributes you are aiming for:
<?php
$f = file_get_contents('inputfile.txt');
$data = json_decode($f);
print_r($data);
echo "Word: " . $data[0]->meta->id . "<br/>";
echo "IPA: " . $data[0]->hwi->prs[0]->ipa . "<br/>";
echo "Part of Speech: " . $data[0]->fl . "<br/>";
echo "Definition: " . $data[0]->shortdef[0] . "<br/>";
echo "Sentence: " . $data[0]->def[0]->sseq[0][0][0] . "<br/>";
echo "T1: " . $data[0]->def[0]->sseq[0][0][1]->dt[1][1][0]->t . "<br/>"; // those can also be in foreach loop, I am just showing the basic example of accessing the attributes
echo "T2: " . $data[0]->def[0]->sseq[0][0][1]->dt[1][1][1]->t . "<br/>";
You can extend this code, or modify yours to add while/foreach loops... as you need them..

php read of a json file - i can not read the multi tier elements

I am trying to read a json file in php, i can retrieve the root parts of the file, however whatever i try, i can not read the innner parts(child) of the json file, any help would be great
here is the json file
{
"orderId":"112-1567223-2156269x",
"legacyOrderItemId":"0218943273x4778",
"orderItemId":"2068965x7409001",
"asin":"B01K9RxxB0GQ",
"title":"xippro decs",
"merchantId":"A3H7UYG3T9xx6JDM",
"quantity":1,
"version3.0":{
"customizationInfo":{
"surfaces":[
{
"name":"Surface 1",
"areas":[
{
"colorName":"White",
"fontFamily":"Coppergate Bold",
"Position":{
"x":13,
"y":218
},
"name":"Line 1",
"Dimensions":{
"width":382,
"height":53
},
"label":"Your Text Here",
"fill":"#FFFFFF",
"customizationType":"TextPrinting",
"text":"Ruth's"
},
{
"colorName":"White",
"fontFamily":"Coppergate Bold",
"Position":{
"x":144,
"y":258
},
"name":"Customization 2",
"Dimensions":{
"width":119,
"height":17
},
"label":"Date (EST)",
"fill":"#FFFFFF",
"customizationType":"TextPrinting",
"text":"1969"
}
]
}
]
}
},
"customizationInfo":{
"aspects":[
{
"title":"Your Text Here",
"text":{
"value":"Ruth's"
},
"font":{
"value":"Coppergate Bold"
},
"color":{
"value":"#FFFFFF"
}
},
{
"title":"Date (EST)",
"text":{
"value":"1969"
},
"font":{
"value":"Coppergate Bold"
},
"color":{
"value":"#FFFFFF"
}
}
]
},
"version":"2.0"
}
and my php code is below
<?php
$file = file_get_contents('16532135318050.json', true);
$character = json_decode($file,false,400);
//print_r ($character);
echo $character->orderId . "<Br>";
echo $character->legacyOrderItemId . "<Br>";
echo $character->orderItemId . "<Br>";
echo $character->asin . "<Br>";
echo $character->merchantId . "<Br>";
echo $character->quantity . "<Br>";
echo $character->version3.0->customizationInfo->surfaces->areas[0]->colorName; // does not work
echo $character->version3.0->customizationInfo->surfaces->areas->colorName; // does not work
?>
Two issues:
version3.0 isn't a valid identifier - you should use {"version3.0"} instead.
surfaces is an array, so you should use surfaces[0]
this might work
$character->{"version3.0"}->customizationInfo->surfaces[0]->areas[0]->colorName
The reason it doesn't work is because $character->version3.0->customizationInfo->surfaces is an array and needs to be dereferenced accordingly:
$character->{'version3.0'}->customizationInfo->surfaces[0]->areas[0]->colorName

array com problema json multidimensional

I am trying to get a data that is in an array inside another array, I did a search by the forum and google and I made several attempts without success.
It seems like an easy catch but I'm breaking my head all day and I can not.
I'm leaving below my JSON code and my last attempt to pass to PHP.
Thankful.
CODE JSON:
{
"ordens_de_servico": [
{
"oser_numero_os": 23932944,
"oser_nome_solicitante": "ED PI - CAMPO MAIOR",
"oser_dt_abertura": "27/03/2018",
"oser_pontos_refer_endereco": null,
"oser_observ_reclamacao": null,
"oser_prioridade": null,
"servico": {
"serv_cod_servico": 60,
"serv_descr_servico": "CORTE POR DEBITO"
},
"cliente": {
"nome": "ANTONIO WELTON DA SILVA OLIVEIRA",
"telefone": " "
},
"unidade_consumidora": {
"unid_ident_uc": 10945024,
"logr_nome_logr_expandido": null,
"medidor": "A2006171",
"latitude": " -4.711808",
"longitude": "-41.793455"
},
"faturas": [
{
"total_fatura": "23.01"
},
{
"total_fatura": "17.88"
},
{
"total_fatura": "23.01"
},
{
"total_fatura": "21.9"
},
{
"total_fatura": "22.92"
}
]
}
]
}
CODE PHP
<?php
// Read JSON file
$json = file_get_contents('oss.json');
//Decode JSON
$json_data = json_decode($json,true);
//Print data
print_r($json_data);
$os = $json_data['ordens_de_servico'][0]['oser_numero_os']. PHP_EOL;
$data = $json_data['ordens_de_servico'][0]['oser_dt_abertura']. PHP_EOL;
$cod_serv = $json_data['ordens_de_servico']['servico'][0]['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico']['faturas'][0]['total_fatura']. PHP_EOL;
echo $os."<p>";
echo $data."<p>";
echo $cod_serv."<p>";
echo $total_fatura."<p>";
?>
I tried looping unsuccessfully on the fatura
$json_data = json_decode($json,false);
foreach ( $json_data->ordens_de_servico as $valor){
echo 'FATURA:'.$valor->faturas->total_fatura."<p>".PHP_EOL;
echo PHP_EOL;
}
At a minimum, you are missing the [0] on these two lines:
$cod_serv = $json_data['ordens_de_servico']['servico'][0]['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico']['faturas'][0]['total_fatura']. PHP_EOL;
They need to be:
$cod_serv = $json_data['ordens_de_servico'][0]['servico']['serv_cod_servico']. PHP_EOL;
$total_fatura = $json_data['ordens_de_servico'][0]['faturas'][0]['total_fatura']. PHP_EOL;
Example of looping through elements in arrays:
foreach($json_data['ordens_de_servico'] as $key => $value){
echo $value["oser_numero_os"];
foreach($json_data['ordens_de_servico'][$key]['faturas'] as $index => $row){
}
}

Parsing JSON with json_decode in PHP

This is the JSON data I get from our ticket-system. I would like to parse it with PHP and save the data in a database to create statistics and a dashboard so everyone can see how many tickets are open and the latest closed tickets.
I can read some of the data but not everything.
{
"address":"belgium",
"workers":{
"peter":{
"worker":"peter",
"open_close_time":"45.6 T/h",
"closed_tickets":841,
"open_tickets":7,
"last_checkin":1498768133,
"days_too_late":0
},
"mark":{
"worker":"mark",
"open_close_time":"45.9 T/h",
"closed_tickets":764,
"open_tickets":2,
"last_checkin":1498768189,
"days_too_late":0
},
"walter":{
"worker":"walter",
"open_close_time":"20.0 T/h",
"closed_tickets":595,
"open_tickets":4,
"last_checkin":1498767862,
"days_too_late":0
}
},
"total_tickets":2213,
"tickets":[
{
"id":2906444760,
"client":"297",
"processed":0
},
{
"id":2260,
"client":"121",
"processed":0
},
{
"id":2424,
"client":"45",
"processed":0
}
],
"last_closed_tickets":[
{
"id":2259,
"client":"341",
"closed_on":"2017-06-25T10:11:00.000Z"
},
{
"id":2258,
"client":"48",
"closed_on":"2017-06-20T18:37:03.000Z"
}
],
"settings":{
"address":"belgium",
"email":"",
"daily_stats":0
},
"open_close_time":"161.1 T/h",
"avgopen_close_time":123298,
"ticket_time":"27.1 T/h",
"stats":{
"time":1498768200087,
"newest_ticket":1498768189000,
"closed_tickets":2200,
"open_tickets":13,
"active_workers":3
},
"avg_paid_tickets":64.55,
"avg_afterservice_tickets":35.45
}
This is the PHP code I tried to get the names of the worker but this doesn't work.
<?php
$string = file_get_contents("example.json");
$json = json_decode($string, true);
echo $json['address'];
foreach($json->workers->new as $entry) {
echo $entry->worker;
}
?>
If I try it like here below it works but then I've got to change the code everytime another employee starts.
echo $json['workers']['mark']['closed_tickets'];
<?php
$string = file_get_contents("example.json");
$json = json_decode($string, true);
foreach($json['workers'] as $entry){
echo $entry['worker'] . " has " . $entry['open_tickets'] . " tickets" . "\n";
}
?>

How to send json data from url to database and update it

Hy,
I just cant figure it out how to get this to work.
How do I post the home>name, home>score to the database (the same for away) and send the status, rounds and datetime to the database.
But if there is a change in the json url than update the database and if there is a new match insert it.
this all needs to be done automatically.
[
{
"url":"http://www.gosugamers.net/counterstrike/tournaments/10423-starladder-cis-minor-championship-cologne-2016/2865-playoffs/10426-playoffs/matches/113497-worst-players-vs-team-empire",
"home":{
"name":"Worst Players",
"url":"/counterstrike/teams/15191-worst-players",
"country":"Russian Federation",
"rank":57,
"score":1
},
"away":{
"name":"Team Empire.",
"url":"/counterstrike/teams/14464-team-empire",
"country":"Russian Federation",
"rank":40,
"score":2
},
"status":"Complete",
"type":"counterstrike",
"rounds":"Best of 3",
"valueBet":true,
"datetime":1462024800
},
{
"url":"http://www.gosugamers.net/counterstrike/tournaments/10296-esports-championship-series-season-1/2810-online-phase/10298-north-american-league/matches/111367-team-liquid-cs-vs-counter-logic-gaming-cs",
"home":{
"name":"Team Liquid.CS",
"url":"/counterstrike/teams/10561-team-liquid-cs",
"country":"United States",
"rank":10
},
"away":{
"name":"Counter Logic Gaming.CS",
"url":"/counterstrike/teams/10569-counter-logic-gaming-cs",
"country":"United States",
"rank":39
},
"status":"Upcoming",
"type":"counterstrike",
"rounds":"Best of 3",
"valueBet":true,
"datetime":1462068000
}
]
I have tried this code
<?php
include("../../check.php");
$urljson = "http://localhost:5000/matches";
$json = file_get_contents($urljson);
$data = json_decode($json, TRUE);
$home = $data[0]['home'];
$away = $data[0]['away'];
$status = $data[0]['status'];
$type = $data[0]['rounds'];
$timestamp = $data[0]['datetime'];
foreach($data as $array) {
echo $home['name'];
echo '<br>';
echo $home['score'];
echo '<br>';
echo $away['name'];
echo '<br>';
echo $away['score'];
echo '<br>';
echo $status;
echo '<br>';
echo $type;
echo '<br>';
echo $timestamp;
echo '<br>';
echo '<br>';
}
?>
but this is what the webpage gave me (it showed mutiple times the same result)
ANOX
Notice: Undefined index: score in C:\xampp\htdocs\main\dashboard\backend\info.php on line 18
Worst Players
Notice: Undefined index: score in C:\xampp\htdocs\main\dashboard\backend\info.php on line 22
Upcoming
Best of 3
1462100400
I hope someone can help me with this beceause I am stuck for like 4 days now.
You get the same data all the time cause you are using the wrong variables inside the loop. Use the $array variable in your case:
foreach($data as $array) {
echo $array['name'];
echo '<br>';
echo $array['score'];
echo '<br>';
... etc.
}
Maybe it would be good to call the variable $row or $match instead of $array for better readability.
You get the "Notice: Undefined..." because there are some JSON nodes where there is no score. Check for score before using it with
if (isset($array['score'])) {
// use it inside if:
echo $array['score']
}
Here the corrected code:
<?php
include("../../check.php");
$urljson = "http://localhost:5000/matches";
$json = file_get_contents($urljson);
$data = json_decode($json, TRUE);
foreach($data as $match) {
echo $match['home']['name'];
echo '<br>';
if (isset($match['home']['score'])) {
echo $match['home']['score'];
echo '<br>';
}
echo $match['away']['name'];
echo '<br>';
if (isset($match['away']['score'])) {
echo $match['away']['score'];
echo '<br>';
}
echo $match['status'];
echo '<br>';
echo $match['rounds'];
echo '<br>';
echo $match['datetime'];
echo '<br>';
echo '<br>';
}
?>

Categories