Inserting data into an array - do not show numbers in json_encode - php

I have this array $fields which is 2D. It's not a standard class and fetched from database. What I need to do is: Insert data into another array and give results like this (JSON encoded):
"fields": {
"0": [{
"field": "text",
"name": "link",
"label": "Link",
"required": true,
"type": "string"
}, {
"field": "xx",
"name": "xx",
"label": "xx",
"required": xx,
"type": "xx"
}],
"1": {
{
"field": "xx",
"name": "xx",
"label": "xx"
},
{
"field": "xx",
"name": "xx",
"label": "xx"
}
}
}
What I get is:
"fields": {
"0": [{
"field": "xx",
"name": "xx",
"label": "xx",
"required": xx,
"type": "xx"
}, {
"field": "xx",
"name": "xx",
"label": "xx",
"required": true,
"type": "xx"
}],
"1": {
"2": {
"field": "xx",
"name": "xx",
"label": "xx"
},
"3": {
"field": "xx",
"name": "xx",
"label": "xx"
},
}
}
Now I need to insert data to $f array and then $f array into array $r. To print like this "1": { or "0": { I use this:
$r = array(
'f' => (object) $f
);
The PHP code:
foreach($fields AS $c => $field) {
$f[$field['id']][$c] = array(
"field" => $field['field'],
"name" => $field['name'],
"label" => $field['label'],
);
if($field['required'] == "1") {
$f[$field['id']][$c]['required'] = true;
}
}
The issue mainly is $c thing, if I just do [] instead of [$c], it makes another array. I use the JSON encoded in JavaScript code and both the JSON encoded result works but I need the first one.

Your first JSON output is invalid. I hope it's just a typo from copying it into the question.
"1": {
{
should be "1": [ {.
If that's the case you can simply renumber the arrays after your code:
foreach($f as &$ff) $ff = array_values($ff);
unset($ff);
Or if you don't know or like references:
foreach($f as $key => $ff) $f[$key] = array_values($ff);
Then json_encode should create the output you want. (PHP arrays result in JSON arrays if the keys are numeric, start from 0, and have no holes; otherwise they will be encoded as JSON objects)
If you want to avoid another loop you could use:
foreach($fields AS $field) {
$f[$field['id']][] = array(
"field" => $field['field'],
"name" => $field['name'],
"label" => $field['label'],
);
//hacky way to get the key of the array just created
$c = count($f[$field['id']) - 1;
if($field['required'] == "1") {
$f[$field['id']][$c]['required'] = true;
}
}
Or create the array first and insert it in the end (a little cleaner imo):
foreach($fields => $field) {
$tmp = array(
"field" => $field['field'],
"name" => $field['name'],
"label" => $field['label'],
);
if($field['required'] == "1") {
$tmp['required'] = true;
}
$f[$field['id']][] = $tmp;
}

Related

PHP - How to change json values according to another json

I am new to PHP programming and I need your lights!
I have a JSON file like:
"data": [{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
}]
and I have to change it using another json file which is like:
"diagnostics_keys": [
{
"ID": 1,
"type": "BTTPV",
"key": "0_193_bttpv",
"unit": "V"
},
{
"ID": 2,
"type": "BTTPC",
"key": "0_195_bttpc",
"unit": "A"
},
{
"ID": 3,
"type": "AVGKMKWH",
"key": "0_202_avgkmKwh",
"unit": "Km/Kwh"
}]
How can I combine these two (using the ID and type keys/values of the second json and replace the DIAGNOSTIC_TYPE_ID with those on first json)and take a result like the bellow json?
"data": [{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
}]
Would anyone have any points or links that may know and may help?
//change to arrays
$data = json_decode(YOUR_DATA_JSON, true); // I don't know your json variable names, so replace them
$diagnosticKeys = json_decode(YOUR_DIAGNOSTIC_KEYS_JSON, true);
//iterate over data, this is the one you want to change
foreach ($data as &$dataItem) {//(& is for replacing the values)
//another foreach for diagnostic keys
foreach ($diagnosticKeys as $diagnosticKey) {
if ($dataItem["DIAGNOSTIC_TYPE_ID"] == $diagnosticKey["ID"] {
$dataItem["DIAGNOSTIC_TYPE_ID"] = $diagnosticKey["type"];
}
}
}
//change to json again
$data = json_encode($data);
Not tested but should work.
$data1 = json_decode($json1);
$data2 = json_decode($json2);
$result = [];
foreach ($data1->data as $key => $value) {
foreach($data2->diagnostics_keys as $i => $val){
if($value->DIAGNOSTIC_TYPE_ID==$val->ID){
$value->DIAGNOSTIC_TYPE_ID = $val->type;
$result[$key]['DIAGNOSTIC_TYPE_ID'] = $val->type;
$result[$key]['VALUE'] = $value->VALUE;
}
}
}
echo json_encode($result);

How to group JsonArray result content in json index

In my JsonArray result, I want to put all the content in index [{'data':{contenthere}}]
Here is my code :
$data = [];
$gr = []; //some data here
foreach($gr as $g) {
$data[] = [
'id' => $g['id'],
'name' => $g['name'],
'phone' => $g['pĥone']
]
}
return $data;
return $data output :
string(249) "[
{
"id": "112",
"name": "john",
"phone": "XXXXXXXXX"
},
{
"id": "213",
"name": "mike",
"phone": "XXXXXXXXX"
},
{
"id": "246",
"name": "jess",
"phone": "XXXXXXXXX"
},
]
cool, now I want to put all this in ['data'] so the result needed :
string(249) "[
{
"data": {
{
"id": "112",
"name": "john",
"phone": "XXXXXXXXX"
},
{
"id": "213",
"name": "mike",
"phone": "XXXXXXXXX"
},
{
"id": "246",
"name": "jess",
"phone": "XXXXXXXXX"
},
}
}
]
As Google JSON Style
I tried the $data[]['data'] but the "data": repeats in each object
foreach($gr as $g) {
$data[]['data'] = ...
I thought do do group_by function but I think that there is a simple solution for that
I'm not sure if you really need the extra array at the top level, but use...
return [["data" => $data]];
should give you the result.
Use json_encode to achieve this:
$json = json_encode(array('data' => $data));
print_r($json);
Result:
{
"data": [
{
"id": "112",
"name": "john",
"phone": "XXXXXXXXX"
},
{
"id": "213",
"name": "mike",
"phone": "XXXXXXXXX"
},
{
"id": "246",
"name": "jess",
"phone": "XXXXXXXXX"
}
]
}

How to get json output from php array

This is my PHP code for json output:
$sql="SELECT id,name FROM languages ORDER BY id";
$result=mysqli_query($conn,$sql);
// Fetch all
$result = mysqli_fetch_all($result,MYSQLI_ASSOC);
$out_put = json_encode($result);
echo $out_put;
This is the json output of the above php code:
{
"0": {
"id": "1",
"name": "English"
},
"1": {
"id": "2",
"name": "Kanada"
},
"2": {
"id": "3",
"name": "Hindi"
},
"3": {
"id": "4",
"name": "Telugu"
}
}
But I want output like this:
{
"Responsecode":200,
"Message":"Sucess",
"languagelist": [
{
"id": "1",
"name": "English"
},
{
"id": "2",
"name": "Kannada"
},
{
"id": "3",
"name": "Hindi"
},
{
"id": "4",
"name": "Telugu"
}
]
}
I am trying to create API and I am new in it. Please help. Thank you in advance.
Just write
$out_put = json_encode([
"Responsecode" => 200,
"Message" => "Sucess",
"languagelist" => $result
]);
You can do it by this way:
$output['Responsecode'] = 200;
$output['Message'] = "Sucess";
$output['languagelist'] = $result;
$out_put = json_encode($output);

With Php in a JSON array how to retrieve the value of an item according to another associated value?

I use json_decode Php function to get a JSON array of countries datas.
{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
},
If I want to retrieve the Code of the 1st element I can do:
$result = json_decode($sXML);
$final = $result->Countries[0]->Name;
And $final will have the value of 'Andorre'.
But what if I want to retrieve the same value 'Andorre' using its correspoding Code ?
Is it possible to do it ?
I know there is an option for the json_function() to obtain an associative array instead of a JSON array, but how would you use it to get the value 'Andorre' using its Code ?
Thank you
<?php
$s = '{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
}
]
}';
$arr = json_decode($s, true);
print_r(array_column($arr['Countries'], "Name", "Code"));
?>
yields
Array
(
[AD] => Andorre
[AE] => Émirats Arabes Unis
[AF] => Afghanistan
[AG] => Antigua-Et-Barbuda
)
Here we are using two function for achieving this array_column and array_combine to retrieve the expected output.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string='{
"Countries":
[
{
"Code": "AD",
"Name": "Andorre"
},
{
"Code": "AE",
"Name": "Émirats Arabes Unis"
},
{
"Code": "AF",
"Name": "Afghanistan"
},
{
"Code": "AG",
"Name": "Antigua-Et-Barbuda"
}
]
}';
$array=json_decode($string,true);
$codes= array_column($array["Countries"], "Code");//Retrieving column code
$names= array_column($array["Countries"], "Name");//Retrieving column name
$data= array_combine($codes, $names); //combining array with code as keys and names as values.
print_r($data);`
Output:
Array
(
[AD] => Andorre
[AE] => Émirats Arabes Unis
[AF] => Afghanistan
[AG] => Antigua-Et-Barbuda
)
I guess you can use something like:
function search_json($obj, $field, $value) {
foreach($obj as $item) {
foreach($item as $child) {
if(isset($child->$field) && $child->$field == $value) {
return $child->Name;
}
}
}
return null;
}
print_r(search_json($result, "Code", "AD"));
# Andorre

Parsing an array with PHP in a foreach loop

I want to parse an array with PHP's foreach loop to get the object names and values inside the 'ques' array.
[
{
"ques": [
{
"name": "comment",
"value": "comment me for the reason",
"sur_id": "1",
"user_id": "admin#gmail.com",
"pagename": "question_response"
},
{
"name": "check-box[]",
"value": "1"
},
{
"name": "radio",
"value": "radio 2"
},
{
"name": "yes",
"value": "no"
}
]
"ques":[
{
"name": "date",
"value": "2015-10-23"
},
{
"name": "select-deopdown",
"value": ""
},
{
"name": "true",
"value": "false"
},
{
"name": "number",
"value": "55"
}
]
}
]
I want to separate the value from the 'ques' array:
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
// print_r($content);
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content, true);
foreach($datas->ques as $values)
{
echo $values->value . "\n";
print_r($values);
}
$test[] = array('ques' => $datas ,'answer'=>$values);
}

Categories