how to convert for loop results in json - php

I Want to convert this php results in to JSON.
for ($i = 0; $i < (count($getnodays)); $i++)
{
$category = $getctgry[$i];
$Priority = $getpriotity[$i];
$NoOfDays = $getnodays[$i];
$StDate = $date1[$i];
$EdDate = $date2[$i];
}
Results Required to be in :
{
"Category": "Category",
"Priority": "Priority1",
"StDate": "1/1/2016",
"EdDate": "5/1/2018"
},{
"Category": "Category",
"Priority": "Priority1",
"StDate": "1/1/2016",
"EdDate": "5/1/2018"
},{
"Category": "Category",
"Priority": "Priority1",
"StDate": "1/1/2016",
"EdDate": "5/1/2018"
}

In your loop, create a new array occurance each iteration.
Then use json_encode() to turn that array into a valid JSON string.
$json = [];
for ($i = 0; $i < (count($getnodays)); $i++) {
$json[] = ['Category' => $getctgry[$i],
'Priority' => $getpriotity[$i],
'NoOfDays' => $getnodays[$i],
'StDate' => $date1[$i],
'EdDate' => $date2[$i],
];
}
echo json_encode($json);

Related

how to solve Array merge for json in this example?

I parse Excel sheet and get this JSON:
[
{
"A":"Samsung",
"Groupe":{
"F":"TV",
"D":"HDR"
}
},
{
"A":null,
"Groupe":{
"F":null,
"D":null
}
},
{
"A":"Sony",
"Groupe":{
"F":"T.V",
"D":"LCD"
}
},
{
"A":"Sony",
"Groupe":{
"F":"PS4",
"D":"Pro edition"
}
},
{
"A":"Sony",
"Groupe":{
"F":"Smart Phone",
"D":"Quad core"
}
}
]
Php code:
$data = [];
for ($row = 15; $row <= 25; $row++) {
$data[] = [
'A' => $worksheet->getCell('A'.$row)->getValue(),
'Groupe' => [
'F' => $worksheet->getCell('F'.$row)->getValue(),
'D' => $worksheet->getCell('D'.$row)->getValue()
]
];
}
How can I organize(sort) json depending on "A"?
I tried this but I still couldn't merge "Groupe" for same "A" together:
Take away NULL colomns.
Create a copy of the Array.
Regroup fields for same element in the new Array(this didnt work)
Code:
$data1 = [];
for ($l = 0; $l < count($data); $l++){
$data1[$l] = $data[$l];
}
for ($j = 0; $j < count($data); $j++) {
if($data[$j]['A'] != NULL){
if($data[$j]['A'] !== $data[$j+1]['A']){
$data1[$j] = $data[$j];
}
else{
$data1[$j]['A']= $data[$j]['A'];
$data1[$j]['Groupe']= array_merge($data[$j]['Groupe'], $data[$j+1]['Groupe']);
}
}
}
EDIT:
The result that I'm getting for $data1 is exactly the same as the input JSON(except that NULL was deleted), so it looks like merge Array didnt work and what I need is:
[
{
"A":"Samsung",
"Groupe":{
"F":"TV",
"D":"HDR"
}
},
{
"A":"Sony",
"Groupe": [{
"F":"T.V",
"D":"LCD"
},{
"F":"PS4",
"D":"Pro edition"
}, {"F":"Smart Phone",
"D":"Quad core"
}]
}]
Plus it's showing me this :
Notice: Undefined offset: 11 in C:\xampp\htdocs\phptoexcel.php on line
43
Line 43: if($data[$j]['A'] !== $data[$j+1]['A']){
Use the A value as key in $data, so you can group by it:
$data = [];
for ($row = 15; $row <= 25; $row++) {
//get A value, skip if A = NULL
$a = $worksheet->getCell('A'.$row)->getValue(),
if($a===NULL)continue;
//get F and D VALUE, skip if one of them = NULL
$f = $worksheet->getCell('F'.$row)->getValue();
$d = $worksheet->getCell('D'.$row)->getValue();
if($f===null || $d===null)continue;
//test if A is a key in $data. If not, create
if(!array_key_exist( $a, $data ){
$data[$a]=[
'A'=>$a,
'Groupe'=>[]
];
}
//Put F and D in a new array in Groupe
$data[$a]['Groupe'][]=["F"=>$f,"D"=>$d];
}
You will end up with:
$data=>
[ "Samsung" =>[ "A" => "Samsung",
"Groupe" => [ 0 =>[ "F" => "TV",
"D" => "HDR"
]
]
],
"Sony" => [ "A" => "Sony",
"Groupe" => [ 0 =>[ "F":"TV",
"D":"HDR"
],
1 =>[ "F":"T.V",
"D":"LCD"
],
2 =>[ "F":"PS4",
"D":"Pro edition"
],
3 =>[ "F":"Smart Phone",
"D":"Quad core"
],
]
]
Try This
$arrUnique = array();
$result = array();
$i=0;
foreach($data as $value){
if($value['A']!=null){
$data1 = [];
$intID = $value['A'];
if( in_array( $intID, $arrUnique ) ) {
$key = array_search ($intID, $arrUnique);
$result[$key]['Groupe'][] = $value['Groupe'];
}else{
$data1['A'] = $value['A'];
$data1['Groupe'][] = $value['Groupe'];
$result[$i]=$data1;
$arrUnique[]=$value['A'];
$i++;
}
}
}
I usually don't perform JSON to JSON transformation using PHP but using jq command line utility.
Given your input JSON file, you can use this jq filter:
jq '[[sort_by(.A)|.[]|select(.A!=null)]|group_by(.A)|.[]as $i|{A:$i[].A,Groupe:$i|map(.Groupe)}]|unique' file
[
{
"A": "Samsung",
"Groupe": [
{
"F": "TV",
"D": "HDR"
}
]
},
{
"A": "Sony",
"Groupe": [
{
"F": "T.V",
"D": "LCD"
},
{
"F": "PS4",
"D": "Pro edition"
},
{
"F": "Smart Phone",
"D": "Quad core"
}
]
}
]

Add another key php array json

Please correct the terminologies that I am using.
I am trying to return a json data like this:
"data": [
{
"id": 1
"name": "test"
},
{
{
"id": 2
"name": "abc"
},
{
"id": 3
"name": "zxc"
}
]
and my code is exactly this one
$data = [];
foreach($prices as $price) {
$data[]["id"] = $price->id;
$data[]["name"] = $price->name;
}
$result["data"] = $data;
the code returns the json like this:
"data": [
{
"id": 1
},
{
"name": "test"
}
{
"id": 2
},
{
"name": "abc"
}
{
"id": 3
},
{
"name": "zxc"
}
]
Sorry for the bad formatting.
Like this
foreach($prices as $price) {
$data[] = [
"id"=> $price->id,
"name" => $price->name
];
}
You are adding the items sequentially, when you need to group them in an array and then add that array as a single unit.
$i = 0;
$data = [];
foreach($prices as $price) {
$data[$i]["id"] = $price->id;
$data[$i]["name"] = $price->name;
$i++;
}
$result["data"] = $data;
The problem is that you keep appending to the array instead of appending to an object and then to the $data array.
Try like this
$data = [];
foreach($prices as $price) {
$topush = [];
$topush["id"] = $price->id;
$topush["name"] = $price->name;
$data[] = $toReturn;
}
$result["data"] = $data;
or, even shorter
$data = [];
foreach($prices as $price) {
$data[] = ['id' => $price->id, 'name' => $price->name];
}
$result["data"] = $data;
You are adding two new Elements to your output, one containing the key/value for id and the other one for name. You have to put both into one element:
$data[]["id"] = $price->id; // Add one element
$data[]["name"] = $price->name; // Add second element
// New
$data[] = ['id' => $price->id, 'name' => $price->name]; // Add both as one Element
Empty [] creates new index every time. You must specify index where you wish to insert:
$data = [];
foreach($prices as $i => $price) {
$data[$i]["id"] = $price->id;
$data[$i]["name"] = $price->name;
}
$result["data"] = $data;
You kept assigning the value to a new key you should assign the data you want bundle in one go.
$data = [];
foreach($prices as $price) {
$data[] = [
"id" => $price->id,
"name" => $price->name;
]
}
$result["data"] = $data;

How can i properly format php array to json?

Here is my code. I'm trying to scrape a table.
$page = file_get_contents('https://www.jncb.com/Support/Help-Resources/Foreign-Exchange-Services');
$dom = new DOMDocument();
$html = $page;
$data = array();
$fx = array();
$cnt = 0;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$my_xpath_query = "//table//tbody[contains(#class, 'FxRContainer')]//td";
$result_rows = $xpath->query($my_xpath_query);
foreach ($result_rows as $key=>$result_object) {
$data[] = $result_object->nodeValue;
}
for ($i=0; $i < 28; ++$i) {
if( $i % 2 == 0 ) {
$fx[] = $data[$i];
}
}
for ($i=0; $i < 14; ++$i) {
if ( $i % 2 == 0 ) {
$fx[$i] = substr($fx[$i], 6);
}
}
print_r($fx);
echo json_encode($fx, JSON_PRETTY_PRINT);
Here are my results:
[
"USD",
"120.00",
"GBP",
"171.20",
"CAD",
"95.50",
"EUR",
"148.30",
"KYD",
"0.00",
"TTD",
"0.00",
"JPY",
"1.11"
]
You're very close.
In order to create JSON from PHP you need an associative array. Right now you have a standard array.
For example:
$associative_array = [
'currency' => 'USD',
'amount' => 120.00
];
OR
$associative_array = [
'USD' => 120.00
];
The exact example for your case:
foreach($result_rows as $key => $result_object) {
// took a guess here
// not entirely sure if you want the $key or the $result_object->nodeValue to be substr'd
$data[$key] = substr($result_object->nodeValue, 6);
}
Then you can use json_encode() to encode it to a JSON object:
$json = json_encode($associative_array);

PHP json_encode creates number index as string instead of an object

I have the following example code in PHP:
$data = array(
'hello',
'world',
'hi'
);
$ret = array();
$ret['test'] = array();
$ret['testing'] = array();
foreach($data as $index => $value){
if($index < 1){
$ret['test'][$index]['val'] = $value;
$ret['test'][$index]['me'] = 'index < 1';
}
else {
$ret['testing'][$index]['val'] = $value;
$ret['testing'][$index]['me'] = 'index >= 1';
}
}
echo json_encode($ret);
I would expect this to be the JSON output:
[{
"test":[
{
"val": "hello",
"me": "index < 1"
}
],
"testing":[
{
"val": "world",
"me": "index >= 1"
},
{
"val": "hi",
"me": "index >= 1"
}
]
}]
However, what ends up happening is that I end up with the following:
[{
"test":[
{
"val": "hello",
"me": "index < 1"
}
],
"testing":{
"1":{
"val": "world",
"me": "index >= 1"
},
"2":{
"val": "hi",
"me": "index >= 1"
}
}
}]
The "1" and "2" keys appear despite being an int and despite the correct rendering of test when the same counter variable is used. Is there a way I can make sure that testing becomes an array of JSON objects?
Because the array doesn't start with index 0 but with index 1, it's encoded as an JSON object instead of an JSON array.
You can use the array_values() function to remove the indexes and only keep the values.
Example:
$ret['testing'] = array_values($ret['testing'])
echo json_encode($ret);
But because you don't need the index at this moment, you can also refactor your code to this:
foreach($data as $index => $value){
if($index < 1){
$ret['test'][] = array(
'val' => $value,
'me' => 'index < 1'
);
}
else {
$ret['testing'][] = array(
'val' => $value,
'me' => 'index >= 1'
);
}
}
echo json_encode($ret);
This way, the arrays will always start with index 0.

MySQL to JSON, how to get the right format?

So, I'm using a PHP-script to output MySQL to JSON, but I'm having trouble figuring out how to output the right JSON-format.
Here's the PHP-script:
$sql_query = "SELECT * FROM DiseaseData";
$res_sql = mysql_query($sql_query) or die(mysql_error());
$arr = array();
if(mysql_num_rows($res_sql) > 0){
ini_set('memory_limit', '-1');
while($row_sql = mysql_fetch_assoc($res_sql)){
$arr[] = $row_sql;
}
$json = json_encode($arr);
$file = '../../files/json/DiseaseData.json';
file_put_contents($file, $json);
}
ini_set('memory_limit', '-1');
Here's the outputted JSON-format:
[{
"ID": "1",
"Magnitude": "0.842",
"County": "Alameda",
"Disease": "E. coli O157",
"lat": "37.7652",
"lng": "-122.242"
}, {
"ID": "2",
"Magnitude": "1.520",
"County": "Alameda",
"Disease": "HIV",
"lat": "37.7652",
"lng": "-122.242"
}]
This is the JSON-format I'd like to have it in:
{
"columns":[{
"fieldName" : "ID",
"position" : 1
},
{
"fieldName" : "Magnitude",
"position" : 2
},
{
"fieldName" : "County",
"position" : 3
},
{
"fieldName" : "Disease",
"position" : 4
},
{
"fieldName" : "lat",
"position" : 5
},
{
"fieldName" : "lng",
"position" : 6
},]
"data": [
[ 1, 0.842, "Alameda", "E. coli O157", 37.7652, -122.242],
[ 2, 1.520, "Alameda", "HIV", 37.7652, -122.242]
]
}
The solution would be like this:
Create two arrays, $columns and $data
In $columns array, store the position and the associated field name
In $data array, insert all data rows using while loop.
Finally, insert both the arrays in $result array and then apply json_enocde() on it.
Here's the code:
// your code
if(mysql_num_rows($res_sql) > 0){
$columns = $data = array();
$max_columns = mysql_num_fields($res_sql);
for($i=0; $i < $max_columns; $i++){
$columns[] = array('fieldName' => mysql_field_name($res_sql, $i), 'position' => $i+1);
}
while($row_sql = mysql_fetch_assoc($res_sql)){
$data[] = array_values($row_sql);
}
$result = array('columns' => $columns, 'data' => $data);
$json = json_encode($result);
// your code
}
Note: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

Categories