Laravel JSON to Array - php

I have to convert json to arry from the laravel notifications table data field,
This is the the data shown on dd($user->notifications);
This is how the response shows in the postman
I need to show the payload within [] as below
{
"payload": [ {
"title": "PHP Developer Accepted",
"description": "<p>This is a professional IT Job </p>",
"user_id": 54,
"job_id": "01"
}],
"message": "",
"result": true
}
Here's my controller index function
protected function index()
{
$user = DeviceAuthenticator::getUserByAccessToken();
foreach ($user->notifications as $notification) {
$notifications = $notification->data;
}
return response()->apiSuccess($notifications);
}
But before I dump the $notifications before response it shows as an array
dd($notifications);

just wrap in [] your variable which will be like
protected function index()
{
$user = DeviceAuthenticator::getUserByAccessToken();
foreach ($user->notifications as $notification) {
$notifications = $notification->data;
}
return response()->apiSuccess([$notifications]); // wrap in array
}
You may need something like this
protected function index()
{
$user = DeviceAuthenticator::getUserByAccessToken();
$notifications = [];
foreach ($user->notifications as $notification) {
$notifications[] = $notification->data;
}
return response()->apiSuccess($notifications);
}
here notifications is an array

You can try adding this
->toArray();

Related

How to show array in Json with Fractal?

I want to save REST API data with array to database, its work, all value save to the table, but i still get error when i want to view the result in json.
Here is my error
"message": "Argument 1 passed to App\\Transformers\\NewLoanOfferTransformer::transform() must be an instance of App\\Model\\AntiAttrition, array given, called in /home/insko23/testing.insko.my/vendor/league/fractal/src/Scope.php on line 338",
My Controller
public function new_loan_offer(Request $request, AntiAttrition $antiattrition)
{
$new = array_map(null, $request->mo_id, $request->id_clrt,$request->TaskID,$request->ACID,$request->CustIDNo);
foreach($new as $new) {
$request = new AntiAttrition;
$request->mo_id = $new[0];
$request->id_clrt = $new[1];
$request->TaskID = $new[2];
$request->ACID = $new[3];
$request->CustIDNo = $new[4];
$request->save();
}
$response = fractal()
->item($new)
->transformWith(new NewLoanOfferTransformer)
->toArray();
return response()->json($response,201);
}
My App\Transformer
<?php
namespace App\Transformers;
use App\Model\AntiAttrition;
use App\Model\SettlementInfo;
use League\Fractal\TransformerAbstract;
class NewLoanOfferTransformer extends TransformerAbstract
{
public function transform (AntiAttrition $antiattrition)
{
return[
'id' => $antiattrition->id,
'mo_id'=> $antiattrition->mo_id,
'assign_by'=> $antiattrition->assigned_by,
'id_clrt' => $antiattrition->id_clrt,
'TaskID'=> $antiattrition->TaskID,
'ACID'=> $antiattrition->ACID,
'CustIDNo'=> $antiattrition->CustIDNo
];
}
}
I want to show the result in json, like below
{
"data": [
{
"mo_id": "123",
"id_clrt": "10000000049",
"ACID": "123",
.....
},
{
"mo_id": "1234",
"id_clrt": "10000000045",
"ACID": "1235",
.....
},
{
"mo_id": "124",
"id_clrt": "10000000044",
"ACID": "1245",
.....
},
],
}
Please help me to solve this problem
In the foreach loop, avoid using same name for array and elements of the array you are iterating over, you can rename foreach($new as $new) to foreach($newArray as $new), or something meaningful with your code logic. Also rather than using $new[0] use $new['mo_id'] for referring to the key of the array

php: combining variable values of the same type?

I am new to PHP coming over from Javascript. I have 2 PHP methods. I'd like to combine them into one endpoint call. Can I push them into the same Array so they can come back in one call with one payload?
public function incompleteOrders()
{
$orders = request()->user()->incompleteOrders();
$data = $orders->toArray();
return response($data, 200);
}
public function finishedOrders()
{
$orders = request()->user()->finishedOrders();
$data = $orders->toArray();
return response($data, 200);
}
You can set multiple keys on the resulting json object, for example:
public function orders()
{
$data = [
'incomplete' => request()->user()->incompleteOrders(),
'finished' => request()->user()-> finishedOrders(),
];
return response($data, 200);
}
The json will look something like this:
{
"finished": [
{
"id": 1
}
],
"incomplete": [
{
"id": 2
},
{
"id": 3
}
]
}
Hello you can fetch the two array and combine them in another array like what we have bellow
public function userOrders()
{
$finishedOrders = request()->user()->finishedOrders();
$incompleteOrders = request()->user()->incompleteOrders();
$data = ["finishedOrders" => $finishedOrders->toArray(), "incompleteOrders" => $incompleteOrders->toArray()];
return response($data, 200);
}
Or you can also use array_merge a php function to merge the two array in one

PHP using json_encode, must output the specific data

I'm currently stuck at this scenario, now the other developer wants to output the API structure as seen on attached image.
json_required_format
But I tried as far as I can but I only got these result:
"all_projects": {
"TEST TOWNHOMES": {
"unit_types": [
{
"unit": "TOWNHOUSE 44.00"
}
]
},
"TEST HOMES": {
"unit_types": [
{
"unit": "DUPLEX WITH OUT GARAGE 44.50"
}
]
},
"TEST HOMES II": {
"unit_types": [
{
"unit": "DUPLEX WITH OUT GARAGE 44.50"
}
]
},
"TEST VILLAGE": {
"unit_types": [
{
"unit": "TOWNHOUSE 44.00"
},
{
"unit": "DUPLEX WITHOUT GARAGE 52.30"
}
]
}
I am using MVC framework,
This is my model looks like:
public function all_south_projects()
{
$this->db->distinct();
return $this->db->select('Project as project_name')->from('lots')
->where('available','YES')
->get()->result();
}
public function get_unit_types($projName)
{
$this->db->distinct();
return $this->db->select('UnitType as unit')->from('lots')
->where('Project',$projName)
->where('Available','YES')
->get()->result();
}
And then my controller is:
$resp = $this->MyModel->all_south_projects();
$test_array = array();
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$allunits = array("unit_types"=>$units);
$allunits = (object) $allunits;
$test_array[$value->project_name] = $allunits;
}
//var_dump($test_array);
$stat = 200;
$message = 'Successfully fetched.';
if(empty($test_array)){
$empty=json_decode('{}');
json_output2($stat,'all_projects',$message,$empty);
}else{
json_output2($stat,'all_projects',$message,$test_array);
}
json_output2 is on my helper to customize json format:
Here is my code:
function json_output2($statusHeader,$responseName,$message,$response)
{
$ci =& get_instance();
$ci->output->set_content_type('application/json');
$ci->output->set_status_header($statusHeader);
$ci->output->set_output(json_encode(array('status' =>
$statusHeader,'message' => $message,$responseName =>$response)));
}
NOTE: Scenario is:
The API must give all the projects having available units,
if the project is available, then it needs to get its corresponding available units to view. I know I can make another API call but this time, we need to improve the UX.
Can someone enlighten me to get through this? Thank you!
Change this part :
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$allunits = array("unit_types"=>$units);
$allunits = (object) $allunits;
$test_array[$value->project_name] = $allunits;
}
To :
foreach ($resp as $value) {
$units = $this->MyModel->get_unit_types($value->project_name);
$test_array[] = [
"project_name" => $value->project_name,
"unit_types" => $units
];
}
You don't have to cast your associative array to object like you did there : $allunits = (object) $allunits; because an associative array will always be serialized as a JSON object (associative arrays do not exist in JSON).

Integrating mailchimp with CRM

Need to get campaign_id with the list_id that I've got. My goal is to get all the campaign data and then sort out using the list_id. I have been able to retrieve the campaign response body, but somehow failing to get the campaign list_id. Any help or a different approach would be appreciated. Sharing my code and mailchimp api related reference.
MailChimp api ref:
"campaigns": [
{
"id": "42694e9e57",
"type": "regular",
"create_time": "2015-09-15T14:40:36+00:00",
"archive_url": "http://",
"status": "save",
"emails_sent": 0,
"send_time": "",
"content_type": "template",
"recipients": {
"list_id": "57afe96172", // this is required
"segment_text": ""
},
My Progress:
public static function getCampaignID($list_id){
$MCcampaigninfo = self::$mc_api->get("/campaigns"); // gives a response consisting 3 rows, required value is in 1st row, which is an array
foreach ($MCcampaigninfo as $key => $value) {
if ($value[8]->'list_id' == $list_id) { //under the 'campaign'array, we need the 9th position property 'recipient'
$campaign_id = $value[12]->'id';
}
}
}
This code assumes the response of $mc_api->get is equal to the JSON you showed in your example
public static function getCampaignID($list_id) {
$campaigns = json_encode(self::$mc_api->get("/campaigns"), true);
$campaignIds = [];
foreach ($campaigns as $campaign) {
//if the list_id matches the current campaign recipients['list_id'] add to the array
if ($campaign['recipients']['list_id'] === $list_id) {
$campaignIds[] = $campaign['id'];
}
}
//return an array with campaignIds
return $campaignIds;
}
Got it working. The api structure seems different in reality from their documentation. Thanks for all the help. Posting my updated code.
public static function getCampaignID($list_id){
$MCcampaigninfo = self::$mc_api->get("/campaigns");
foreach ($MCcampaigninfo as $key => $campaign) {
if($key == campaigns){
foreach ($campaign as $key2 => $clist) {
foreach ($clist as $key3 => $recip) {
if($key3 == id){
$campaign_id = $recip;
}
elseif($key3 == recipients){
foreach($recip as $key4 => $listid){
if($key4 == list_id){
if($listid == $list_id){
return $campaign_id;
}
}
}
}
}
}
}
}
}

Why does my php function not get data from JSON array?

I have a page that pulls information about TV shows from the TMDB as a json array with the help of the TMDB-API Wrapper. I am trying to get the page to display information on a tv shows's ['network'].
I have written a function for this that loops through the network array but I can't get it to work. Can anyone tell me what I'm doing wrong? Thanks.
This is my function that does not work.
//Get networks
public function getNetworks() {
$networks = array();
foreach($this->_data['networks'] as $data){
$networks[] = new Network($data, $this->getName());
}
return $networks;
}
Display.php
//Call the function and loop though results
echo ' <li>Networks: <ul>';
$networks = $tvShow->getNetworks();
foreach($networks as $network){
echo '<li>'. $network->getID() .'</li>';
}
This does work (written in the wrapper not me)
public function getSeasons() {
$seasons = array();
foreach($this->_data['seasons'] as $data){
$seasons[] = new Season($data, $this->getID());
}
return $seasons;
}
This does work
//Get Network
public function getNetworks() {
return $this->_data['networks'][0]['name'];
}
And then on display.php
echo '<b>'. $tvShow->getNetworks() .'</b>';
This is the json array
{
"backdrop_path": "/c8A5IYqIT1ez15sqA8wX5tCDTmF.jpg",
"created_by": [
{
"id": 1187819,
"name": "Matthew Weiner",
"profile_path": null
}
],
"episode_run_time": [
47,
45
],
"first_air_date": "2007-07-19",
"genres": [
{
"id": 18,
"name": "Drama"
}
],
"homepage": "http://www.amc.com/shows/mad-men",
"id": 1104,
"in_production": false,
"languages": [
"en"
],
"last_air_date": "2015-05-17",
"name": "Mad Men",
"networks": [
{
"id": 174,
"name": "AMC"
}
],
Tvshow Class
class TVShow{
//------------------------------------------------------------------------------
// Class Variables
//------------------------------------------------------------------------------
private $_data;
/**
* Construct Class
*
* #param array $data An array with the data of the TVShow
*/
public function __construct($data) {
$this->_data = $data;
}

Categories