How to convert multiple objects into 1 JSON string in PHP - php

My application has a list of reports and each 'Report' is defined as a new object in PHP. I'm trying to make a basic API and I want to show a list of all the 'Reports' in 1 JSON string. My code below works well for encoding 1 object into JSON, but how do I get ALL objects and turn ALL of them into 1 long JSON string?
I understand I could make an array of objects, but that returns these brackets [] and I don't want those brackets in the JSON string.
class report {
public $report_name;
public $report_value;
public $report_benchmark;
public $report_result;
public function __construct($report_name, $report_value, $report_benchmark, $report_result) {
$this->report_name = $report_name;
$this->report_value = $report_value;
$this->report_benchmark = $report_benchmark;
$this->report_result = $report_result;
}
}
$item = new report('test', 0, 0, 'OK');
echo json_encode($item, JSON_PRETTY_PRINT);

As suggested by #JimL, you can simply add some objects in an array, which you can encode as json latter on.
$item = array();
$item[] = new report('test', 0, 0, 'OK');
$item[] = new report('test2', 0, 0, 'OK');
echo json_encode($item, JSON_PRETTY_PRINT);
produces:
[{
"report_name": "test",
"report_value": 0,
"report_benchmark": 0,
"report_result": "OK"
}, {
"report_name": "test",
"report_value": 0,
"report_benchmark": 0,
"report_result": "OK"
}]
Note here that you can validate the produced json here

You can do some thing like this.
$item = array();
$item['report1'] = $item = new report('test', 0, 0, 'OK');
$item['report2'] = $item = new report2('test', 0, 0, 'OK');
$item['report3'] = $item = new report3('test', 0, 0, 'OK');
echo json_encode($item, JSON_PRETTY_PRINT);
make an associative array and add assign all objects a meaning full key, which will help to easy access each specific report.

Related

How to format a decimal number from a json object in PHP?

I'm trying to format a decimal number that I've optained from a json object in PHP. My objective is to keep this number with just two places after the comma.
Here is the code:
`
$url = "https://api.yadio.io/exrates/EUR";
$data = json_decode(file_get_contents($url, true));
$object = $data;
foreach($object as $a){
echo round($a->CUP, 2);
}
`
The result without round() was 163.905765, so when I apply it, the result is 0163.9100 and should be 163.90.
Any help will be very appretiate.
Your json response is of type -
{
"BTC": 20849.71,
"EUR": {
"CAD": 1.353201,
"CDF": 2030.444751,
"CHF": 0.990328,
"CLP": 939.150233,
"CNY": 7.204403,
"COP": 4731.844098,
"CRC": 617.225833,
"CUP": 163.905765,
},
"base": "EUR",
"timestamp": 1666977603763
}
So you are not looping around it correctly.
try this -
$url = "https://api.yadio.io/exrates/EUR";
$data = json_decode(file_get_contents($url, true));
$object = $data;
echo round($object->EUR->CUP,2);

Filter two arrays of objects

I'm trying to use array_filter to filter an array of objects, they share a common value which is warehouse_id.
$warehouse_1 = new warehouse(1, 100, [1,2,3,4]);
$warehouse_2 = new warehouse(2, 1100, [1,2,3,4]);
$warehouse_3 = new warehouse(3, 12000, [1,2,3,4]);
$warehouse_4 = new warehouse(4, 130000, [1,2,3,4]);
$warehouse_5 = new warehouse(5, 1400000, [1,2,3,4]);
$inventory_feed_1 = new inventory_feed(12, 1, "2as21332kjd");
$inventory_feed_2 = new inventory_feed(10, 2, "2123asagfrtsdd");
$inventory_feed_3 = new inventory_feed(11, 3, "2as1231sds2d");
$inventory_feed_4 = new inventory_feed(13, 4, "2as1231sds2d");
$inventory_feed_5 = new inventory_feed(14, 5, "2as1231sds2d");
$ifeeds = ["a" => $inventory_feed_1, "b" => $inventory_feed_2, "c" => $inventory_feed_3];
$warehouses = [$warehouse_1, $warehouse_2, $warehouse_3, $warehouse_4, $warehouse_5];
$warehouses_filtered = array_filter(
$warehouses,
function ($warehouse) use ($ifeeds) {
foreach($ifeeds as $ifeed_id => $ifeed) {
return $ifeed->getWarehouseId() == $warehouse->getId();
});
echo count($warehouses_filtered);
The desired output should be [$warehouse_1, $warehouse_2, $warehouse_3]
but it always returns me the original one (5)
You're returning on the first iteration of the foreach loop, so you're only testing whether the warehouse matches the first feed.
You should return true as soon as you find a match, but not return false until you get all the way through the loop without finding a match.
$warehouses_filtered = array_filter(
$warehouses,
function ($warehouse) use ($ifeeds) {
foreach($ifeeds as $ifeed_id => $ifeed) {
if ($ifeed->getWarehouseId() == $warehouse->getId()) {
return true;
}
}
return false;
});
DEMO

PHP JSON Array Get Value

I need PHP JSON help.
I have current output :
{
"status": 200,
"response_msec": 15,
"data": {
"android": {
"test1": 15,
"test2": 6,
"test3": 15,
"test4": 101,
"test5": 87,
"test6": 8,
"test9": 119,
"test10": 101,
"test11": 107
}
}
}
I need print this value : test1 , test2 , test3 ...,test11 .
I have tested some method :
$json = json_decode($result, true);
$dec = (Array)json_decode($result);
print_r ($dec["android"]);
and
foreach ($array as $value)
{
echo $value->android;
}
But not work.
You are missing the ['data'] key,
<?php
$json = '{"status":200,"response_msec":15,"data":{"android":{"test1":15,"test2":6,"test3":15,"test4":101,"test5":87,"test6":8,"test9":119,"test10":101,"test11":107}}}';
$array = json_decode($json, true);
var_dump(array_keys($array['data']['android']));
Check here i have made a php sandbox http://sandbox.onlinephpfunctions.com/code/6f97a9bb499b54919b40d4d12f49049fdd732aef
Also, You can use the function array_keys() to get only the keys of an array, that's what i did.
Your code should work if the json string is assigned to $value. It's just you forgot to include to get the data "data" from "value". Your 3rd line of the first method should look like this:
print_r ($dec["data"]["android"]);
Have a great day

Convert array to JSON in proper format

I'm trying to convert my array to JSON.
My JSON is stored in the database and will later be decoded for permission checking.
Example,
How I want it to be stored in the database:
{ "admin": 1,
"create_posts": 1,
"edit_posts": 1,
"delete_posts": 1 }
How it is being stored now:
{"0":"\"admin\": 1",
"1":"\"create_posts\": 1",
"2":"\"edit_posts\": 1",
"3":"\"delete_posts\": 1"}
My code:
$check_list = $_POST['check_list'];
$list = array();
foreach($check_list as $key) {
$key = '"' . $key .= '": 1';
array_push($list, $key);
}
$json = json_encode($list, JSON_FORCE_OBJECT);
How would I make it so that it stores in the database like I want it to be?
I'm quite new to this, so any hints instead of direct answers is also much appreciated!
UPDATE:
JSON decode and validation:
$permis = json_decode($permissions->permissions, true);
echo ($permis['admin'] == true) ? 'allowed' : 'disallowed';
$arr = [ 'a', 'b', 'c' ];
echo json_encode(
array_combine(
$arr,
array_fill(0, count($arr), 1)
),
JSON_PRETTY_PRINT
);
Output:
{
"a": 1,
"b": 1,
"c": 1
}
http://us3.php.net/manual/en/function.array-combine.php
http://us3.php.net/manual/en/function.array-fill.php
I'm assuming the incoming data looks like this.
$incoming_data = "admin=1&create_posts=1&edit_posts=1&delete_posts=1";
$pairs = parse_str($incoming_data);
so we take the incoming pairs and use the $key as the array index so you don't get the extra array element index.
$permissions = array();
foreach($pairs as $key => $value){
$permissions[$key] = $value;
}
then we encode the new array to get the JSON you're looking for.
print json_encode($permissions);
will print out JSON like this:
{
"admin":"1",
"create_posts":"1",
"edit_posts":"1",
"delete_posts":"1"
}
The main thing to change in your code is this.
foreach($check_list as $key) {
$list[$key] = 1;
}

How to write this json data in array form

{
"phone_number": "918358808742",
"confirmation_token": "c86798c29bd811e58f5822000b9964d9",
"experiment_data": {
"opt_in_consent": 7,
"conf_code_auto_submit_ff": 1,
"manual_referral_code_switch": 1,
"conf_code_auto_submit": 1,
"registration_reminders": 1,
"reengagement_gcm_switch": 1,
"kraken_app_progress_meter_v2": 1,
"kraken_background_service_control": 1,
"modified_sms_confirmation_page": 1,
"auto_sms_confirmation": 1,
"registration_express": 1,
"tutorial_before_offer_start": 1,
"fb_connect_active": 1,
"fb_connect_required_for_login": 1,
"auto_sms_confirmation_v2": 1,
"pwd_input_variations": 4,
"registration_reminder_notifications": 1,
"track_adwords_install": 1
},
"member_id": "a2mx2z"
}
I want this data to be in array form any help will be appreciated
You could use json_decode() function, here a simple exmple
$json = {};
$array = json_decode($json, true); // if you would like arrays
$object = json_decode($json); // if you would like object
echo $array['phone_number']; // array example
echo $object->phone_number; // object example
if you would like to test the validation of your json before decode it you can do it using json_encode() function
$json = {};
if(json_encode($json) == false) {
die("incorrect json !");
} else {
// do the decoding
}

Categories