Parsing Duplicatable Form's JSON data to PHP for Mail - php

I have a form where there are duplicate-able fields and it produces the following JSON data:
{
"mainmember": [
{
"name": "testtest",
"surname": "test",
"id": "8509295266086",
"age": "27",
"gender": "Male",
"townofbirth": "george",
"email": "test#test.com",
"contact": "0112121211",
"passport": "1111111111111",
"postal": "grjiubrwg",
"postal_code": "0010",
"residential": "tytyytyttyytyt",
"residential_code": "4422"
}
],
"dependant1": [
{
"name": "testDUP",
"surname": "testDUP",
"id": "4802235040081",
"age": "64",
"gender": "Male",
"townofbirth": "tehjte",
"cell": "4774811845",
"email": "testDUP",
"passport": "8202255133088",
"relationship": "spouse"
}
],
"dependant2": [
{
"name": "testDUP2",
"surname": "testDUP2",
"id": "1111111111111",
"age": "45",
"gender": "F",
"townofbirth": "knysnasw",
"cell": "0000000000",
"email": "testDUP2",
"passport": "2222222222222",
"relationship": "inlaw"
}
]
}
now the duplicate-able fields are the dependants, in this JSON there's 2 dependant but on duplication it increases to "dependant3, dependant4, dependant5".
Currently when i submit and send to PHP i can count the dependants:
<?php
$json = $_POST['parameters'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
$datasetCount = count($data); // returns count of array items of any array
echo "<h1>There are $datasetCount Dependants</h1>";
$i = 0;
foreach ($data as $each_dep) {
$i++;
echo "<h2>Dependant $i</h2>";
while (list($key, $value) = each ($each_dep)) {
echo "$key: $value<br />";
}
}
?>
and the jQuery send function I'm using:
jQuery('#submit').click(function(){
jQuery('div[class*="mainmember"]').each(function(k, v){
mainmember = {};
mainmember['id'] = '';
$(v).find('.id').each(function(){
mainmember['id'] += $(this).val();
});
mainmember['age'] = '';
$(v).find('.age').each(function(){
mainmember['age'] += $(this).val();
});
mainmember['gender'] = $(v).find('.gender').val();
result['mainmember'] = [mainmember];
});
jQuery('div[class*="dependant"]').each(function(k, v){
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['id'] = '';
$(v).find('.id').each(function(){
dependants['id'] += $(this).val();
});
dependants['age'] = '';
$(v).find('.age').each(function(){
dependants['age'] += $(this).val();
});
dependants['gender'] = $(v).find('.gender').val();
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
I just cant get the other data, such as name, surname etc.
I need to parse it like this to an email:
Main Member:
details
Dependant 2:
details
Dependant 3:
details
Any Help greatly appreciated.

Your json structure is quite painful, you seem to be creating arrays of a single object.
Instead you should have arrays of objects, or single objects referenced by keys.
Ideally for your structure, I think you should have an array of objects for the dependents and a single object for the mainmember, like this:
{
"mainmember": {
"name": "test2",
"id": "1111111111111",
"age": "45",
"gender": "M",
"townofbirth": "knysna",
"email": "tjyrrtjhe",
"contact": "1111111111",
"passport": "5555555555555",
"postal": "yrtjyt",
"postal_code": "1101",
"residential": "tkyutk",
"residential_code": "5555"
},
"dependants": [
{
"name": "dtjtet",
"surname": "grwwr",
"id": "1111222222222",
"age": "48",
"gender": "F",
"townofbirth": "knmysn",
"cell": "0045128588",
"email": "fae#gmail.COM",
"passport": "1212112111111",
"relationship": "spouse"
},
{
"name": "dtjtet2",
"surname": "grwwr2",
"id": "11112222222222",
"age": "44",
"gender": "M",
"townofbirth": "knmysn",
"cell": "0045128588",
"email": "fae#gmail.COM",
"passport": "1212112111111",
"relationship": "spouse"
}
]
}
This way you have a single "mainmember" object, and an array of dependents.
Then with php code like the following you can print the details for it:
<?php
function printMember($member) {
foreach($member as $key=>$value) {
echo "$key : $value <br />";
}
}
$json = $_POST['parameters'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
$depCount = count($data["dependants"]);
echo "<h1>There are $depCount Dependants</h1>";
echo "<h2>Main member data:</h2>";
printMember($data["mainmember"]);
foreach ($data["dependants"] as $index => $dependant) {
echo "<h2>Dependant $index</h2>";
printMember($dependant);
}
To create the correct json structure in the jquery code, something like this:
jQuery('#submit').click(function(){
jQuery('div[class*="mainmember"]').each(function(k, v){
mainmember = {};
mainmember['id'] = '';
$(v).find('.id').each(function(){
mainmember['id'] += $(this).val();
});
mainmember['age'] = '';
$(v).find('.age').each(function(){
mainmember['age'] += $(this).val();
});
mainmember['gender'] = $(v).find('.gender').val();
//This is changed: Remove the [] from around the mainmember,
//should be a single object not an array
result['mainmember'] = mainmember;
});
//create the array of dependants
result['dependants'] = [];
jQuery('div[class*="dependant"]').each(function(k, v){
dependant = {};
dependant['id'] = '';
$(v).find('.id').each(function(){
dependant['id'] += $(this).val();
});
dependant['age'] = '';
$(v).find('.age').each(function(){
dependant['age'] += $(this).val();
});
dependant['gender'] = $(v).find('.gender').val();
//add the dependant to the array
result['dependants'].push(dependant);
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
This is untested but should help you proceed. Your problem is because you are using arrays of single objects instead of the object itself.

Related

Issue with single quote in multiple line json data in php

$arr = '{
"38": {
"email": "zhangshizhu08#163.com",
"history": "Baldwin's,DNW"
},
"39": {
"email": "john#filcombe.com",
"history": "Spink"
},
}';
$p_array = json_decode($dat,true);
print_r($p_array);
Try to use heredoc this way
$jsonString = <<<JSON
{
"38": {
"email": "zhangshizhu08#163.com",
"history": "Baldwin's,DNW"
},
"39": {
"email": "john#filcombe.com",
"history": "Spink"
}
}
JSON;
$p_array = json_decode($jsonString, true);
print_r($p_array);
Hope this helps.

Array for subseries on highcharts Drilldown

I'm having some problems generating graphs with drilldown in Highcharts.
I'm using Highcharts to render a pie with drilldown series.
I need to transform this output json
Drilldownseries = [
{
"name": "LAZIO",
"data": [["ROMA", 28]],
"id": "LAZIO"
},
{
"name": "LAZIO",
"data": [["FROSINONE", 218]],
"id": "LAZIO"
},
{
"name": "LAZIO",
"data": [["LATINA", 212]],
"id": "LAZIO"
},
{
"name": "TOSCANA",
"data": [["FIRENZE", 2]],
"id": "TOSCANA"
},
{
"name": "TOSCANA",
"data": [["LIVORNO", 5]],
"id": "TOSCANA"
},
{
"name": "TOSCANA",
"data": [["PISA", 9]],
"id": "TOSCANA"
}
];
to
Drilldownseries = [
{
"name": "LAZIO",
"data": [["ROMA", 28], ["FROSINONE", 218], ["LATINA", 212]],
"id": "LAZIO"
},
{
"name": "TOSCANA",
"data": [["FIRENZE", 2], ["LIVORNO", 5], ["PISA", 9]],
"id": "TOSCANA"
}
];
This is the part of query that populates the array:
...
if($res3)
{
$i = 0;
while ($row = mysqli_fetch_array($res3, MYSQLI_ASSOC))
{
$row3[$i]["name"] = $row["name"];
$row3[$i]["data"] = [[$row["subname"],$row["data"]]];
$row3[$i]["id"] = $row["id"];
$i++;
};
$row3 = json_encode($row3,JSON_NUMERIC_CHECK);
};
I'd prefer to extract the array with php well formed, but should be the same tranform the json.
PHP 7.2
Highcharts 6.1.1
for benefit of all, this is my solution. Code refined should be appreciated :)
First removed square brackets in code below
$row3[$i]["data"] = [$row["subname"],$row["data"]];
then create the new array so
$repl = array();
$i = 0;
foreach ($row3 as $value) {
if (!isset($repl[$i]['id'])) {
$repl[$i]['id'] = $value['id'];
$repl[$i]['name'] = $value['name'];
$repl[$i]['data'] = [$value['data']];
} elseif (($repl[$i]['id']) <>$value['id']) {
$i++;
$repl[$i]['id'] = $value['id'];
$repl[$i]['name'] = $value['name'];
$repl[$i]['data'] = [$value['data']];
} else {
array_push($repl[$i]['data'], $value['data']);
}
}
$resultx = json_encode($repl,JSON_NUMERIC_CHECK);
thanks

PHP convert JSON array to nested

I'm trying to get JSON by name and save it as a variable with everything related to that nest,
what would the best way to accomplish this?
(in my scenario the names are unique)
[{
"name": "Joe",
"age": "30",
"gender": "male"
},
{
"name": "Logan",
"age": "27",
"gender": "male"
}]
to something like this
{
"Joe": [{
"name": "Joe",
"age": "30",
"gender": "male"
}],
"Logan": [{
"name": "Logan",
"age": "27",
"gender": "male"
}]
}
i need to be able to search on the name to get the correct one, the API switches order so can't get it from just id
Hi This might helps you
$list = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}]';
$newjson = json_decode($list, true);
$final = [];
foreach ($newjson as $key => $value) {
$final[$value['name']][]=$value;
}
$finaloutput = json_encode($final, true);
echo "<pre>";
print_r($finaloutput);
echo "</pre>";
exit;
The output is
{"Joe":
[{"name":"Joe","age":"30","gender":"male"}],
"Logan":
[{"name":"Logan","age":"27","gender":"male"}]}
The Laravel Collections Library is a very useful lib to use cases like yours.
For this problem you could use the keyBy method!
$json = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}
]';
$array = collect(json_decode($json, true))->keyBy('name')->all();
print_r($array); // will be the array with the keys defined by the name!
See https://laravel.com/docs/5.5/collections#method-keyby

Retrieve data (single field) from remote JSON file with PHP

i need to extract one field from a JSON file. From other questiones i've manage to come to this code but the output is a blank page. Can you see what this n00b doing wrong?
<?php
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json);
$tasa=$details->USD[0]->transferencia;
echo .$tasa.;
?>
The json file looks like this:
{
"_antibloqueo": {
"mobile": "https://dkqrwi4z9077n.cloudfront.net",
"video": "https://www.youtube.com/embed/videoseries?list=PL6qOmJKmpQ8QMt20uG_dlh9-jzjcvZOxU&showinfo=0",
"corto_alternativo": "https://bit.ly/venezuela911",
"enable_iads": "1",
"alternativo": "68747470733a2f2f643271737267626d6d76366561752e636c6f756466726f6e742e6e6574",
"alternativo2": "68747470733a2f2f73686431613934666462346474697662672e776f726473736c2e6e6574",
"resource_id": "33504 C"
},
"_labels": {
"a": "DOLARTODAY",
"b": "IMPLICITO",
"c": "SIMADI",
"d": "SICAD 2",
"e": "CENCOEX"
},
"_timestamp": {
"epoch": "1434016329",
"fecha": "Junio 11, 2015 05:22 AM",
"fecha_corta": "Jun 11, 2015",
"fecha_nice": "Junio 11, 2015",
"dia": "Jueves",
"dia_corta": "Jue"
},
"USD": {
"transferencia": 414.18,
"transfer_cucuta": 435.00,
"efectivo": 145.72,
"efectivo_real": 357.61,
"promedio": 414.18,
"promedio_real": 195.94,
"cencoex": 6.30,
"sicad1": 12.00,
"sicad2": 195.94,
"dolartoday": 414.18
},
"EUR": {
"transferencia": 466.57,
"transfer_cucuta": 489.98,
"efectivo": 164.14,
"efectivo_real": 402.84,
"promedio": 466.57,
"promedio_real": 220.71,
"cencoex": 7.10,
"sicad1": 13.52,
"sicad2": 220.71,
"dolartoday": 466.57
},
"COL": {
"compra": 6.70,
"venta": 7
},
"GOLD": {
"rate": 1180.0500
},
"USDVEF": {
"rate": 6.3500
},
"USDCOL": {
"rate": 2775.00,
"ratecash": 2396.00,
"ratetrm": 2523.00,
"trmfactor": 0.1,
"trmfactorcash": 0.05
},
"EURUSD": {
"rate": 1.1264
},
"BCV": {
"fecha": "1433824200",
"fecha_nice": "Junio 9, 2015",
"liquidez": "2.457.797.346",
"reservas": "16.867.000"
}
}
You just make mistake in USD[0] and 2 dots when echoing $tasa
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json);
$tasa=$details->USD->transferencia;
echo $tasa;
I have tested your json, you can access data via multidimensional arrays like below:
<?php
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json , true);
print_r( $details['USD']['transferencia'] );
?>
Try this:
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json, TRUE);
var_dump($details['USD']['transferencia']);

formatted json format in php webservices

I am new in PHP. I am trying to format JSON. Here's the relevant code:
$query = mysql_query("SELECT *
FROM `micards` m
JOIN user u ON m.`mobile` = u.phone");
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
}
echo json_encode($response);
I'm getting this output:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "vwxy#test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "919898989898",
"0": {
"card": {
"name": "abcd",
"email": "rstp#test.com",
"mobile": "919898989898"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "pan",
"email": "pnqr#gmail.com",
"mobile": "8686868686"
}
}
}, {
"phone": "8686868686",
"0": {
"card": {
"name": "monk",
"email": "abcd#gmail.com",
"mobile": "8686868686"
}
}
}]
}
But I want it to be:
{
"success": 1,
"contacts": [{
"phone": "919898989898",
{
"card": {
"name": "abcd",
"email": "vwxy#test.com",
"mobile": "919898989898"
}
},
{
"card": {
"name": "abcd",
"email": "rstp#test.com",
"mobile": "919898989898"
}
}
}],
[{
"phone": "8686868686",
{
"card": {
"name": "panky",
"email": "pnqr#gmail.com",
"mobile": "8686868686"
}
},
{
"card": {
"name": "panky",
"email": "abcd#gmail.com",
"mobile": "8686868686"
}
}
}]
}
What can I do to get the above output?
just change this part:
$phone[] = array('phone'=>$row["phone"],array('card'=>$name));
$response["contacts"] = $phone;
to
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));
Just copy and paste this code
while ($row = mysql_fetch_assoc($query)) {
$response["success"] = 1;
$name = array('name'=>$row["name"],'email'=>$row["email"],'mobile'=>$row["mobile"]);
$response["contacts"][] = array('phone'=>$row["phone"],array('card'=>$name));
}
Please change
$phone[] = array('phone'=>$row["phone"],array('card'=>$name)) to
$phone[] = array('phone'=>$row["phone"],'card'=>$name)
;
My guess is that there is a problem with associative arrays and the way you are packing it. You can try to organize your response array like this:
$response = [
'success'=>1,
'contacts'=>[
'phone'=>$row['phone'],
'card'=>[
'name'=>$row['name'],
'email'=>$row['email'],
'mobile'=>$row['mobile']
]
]
];
It should work, didn't check it out thou.

Categories