I want to use decoded JSON data as php objects to be able to used as follows:
return $data->title
however im running into a few errors. I am able to connect to the remote API url and get the requested data.
$api = 'https://remote.api.url/dataset/list';
$json = file_get_contents($api);
$data = json_decode($json, true);
dd($data);
When i die and dump the data i see the following:
array:1 [▼
"data" => array:5 [▼
0 => array:5 [▼
"id" => "qk4GtMb8"
"title" => "SSA's palliative care has an mHealth deficit "
"image" => "http://gstatic.acfee.org/akamaihd/i/52fdb957187"
"published_at" => "2016-06-10 08:05:00"
"created_at" => array:3 [▼
"date" => "2016-06-07 05:48:34.000000"
"timezone_type" => 3
"timezone" => "UTC"
]
]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
]
]
But i am unable to use the recieved data in object form. return $data->title;
i am pretty new to JSON any help would be appreciated.
Thanks in advance.
The second parameter of json_decode (which in your case is true) converts the objects to array. From official PHP docs: When TRUE, returned objects will be converted into associative arrays. So if you remove it you should be ok.
Related
I'm playing with API responses for a while and I can't convert them into Laravel collection format.
My response after $users = json_decode($users, true); is something like that:
array:2 [▼
"#odata.context" => "https://URL/Something.svc/$metadata#Something"
"value" => array:190 [▼
0 => array:18 [▶]
1 => array:18 [▶]
2 => array:18 [▶]
3 => array:18 [▶]
4 => array:18 [▶]
5 => array:18 [▶]
6 => array:18 [▶]
7 => array:18 [▶]
I need to convert it into Laravel collection so instead of original json_decode I have to use:
$users = collect(array_values(json_decode($users, true))[1]);
It works, but I felt that this is not the right way to do that? Also, I have to use [1] at the end. What's if the array is empty and [1] does not exist? Do I need to validate if it exists or if there is a proper way to deal with this conversion?
After decoding the data you will have an associative array where you can access the data inside the 'value' array directly using $users['value'], so there is not need to use the array_values function.
$users = json_decode($users, true);
if (isset($users['value'])) {
$usersCollection = collect($users['value']);
}
I guess something like this should work fine.
Hello Geeks i am stuck here. I am beginner and want to know how to save and update array data in database.
this is laravel form requested data
I want to save data like this :
mysql database
here is my form request, i want to save data in mysql database, with new row :
"_token" => "FoyoYvFXmNAggbQuMq6PN243QS43MkY99Nq3UAni"
"description" => array:2 [▼
0 => "<h3>Shared Hosting Plan</h3>"
1 => "<h3>Cloud Hosting Plan</h3>"
]
"site_id" => array:2 [▼
0 => "5361"
1 => "5361"
]
"category_id" => array:2 [▼
0 => "1"
1 => "3"
]
"field_1" => array:2 [▶]
"field_2" => array:2 [▶]
"field_3" => array:2 [▶]
"field_4" => array:2 [▶]
"field_5" => array:1 [▶]
"price" => array:2 [▶]
"update_plan" => "Save Plans"
]```
Try like this
$save_data=[];
foreach($data['description'] as $key=>$desc){
$save_data[]=[
'description'=>$desc,
'site_id'=>$data['site_id'][$key],
'category_id'=>$data['category_id'][$key],
'feature_field_1'=>$data['field_1'][$key],
'feature_field_2'=>$data['field_2'][$key],
'feature_field_3'=>$data['field_3'][$key],
'feature_field_4'=>$data['field_4'][$key],
'feature_field_5'=>$data['field_5'][$key],
'price'=>$data['price'][$key]
]
}
\DB::table('table')->insert($save_data);
You can insert like this
Eloquent approach
Model::insert($data);
Query Builder approach
DB::table('table')->insert($data);
I have a deployments Laravel Collection like this:
Illuminate\Support\Collection {#415 ▼
#items: array:5 [▼
0 => array:7 [▼
"id" => 31
"status" => "active"
"name" => "Deployment 1"
"spots" => array:4 [▼
0 => array:2 [▼
"id" => 33
"status" => "active" <-- Want to change this
]
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
]
"data" => array:3 [▶]
]
1 => array:7 [▶]
2 => array:7 [▶]
3 => array:7 [▶]
4 => array:7 [▶]
]
}
I want to update the nested status value to inactive. I have used the Laravel map function, but it only seems to work on collections that have one nesting level. So this...
$this->deployments->map(function ($deployment) {
$deployment['spots'][0]['status'] = 'inactive';
});
dd($this->deployments);
...leaves $this->deployments untouched.
Also tried using nested map functions obtaining a Call to a member function map() on array exception on second level as second and next nesting levels are considered arrays...
Any thoughts?
Thanks in advance.
With the map method, you are almost there. You will have to return the change made in $deployment and do an ->all() at the end to update the collection with the modified values.
For updating a single spot:
$deployments = $deployments->map(function($deployment){
$deployment['spots'][0]['status'] = 'inactive';
return $deployment;
})->all();
For updating all spots:
$deployments = $deployments->map(function($deployment){
foreach($deployment['spots'] as &$spot){
$spot['status'] = 'inactive';
}
return $deployment;
})->all();
For anyone researching this, a more elegant solution might be:
For updating a single spot:
$data = $deployments->all();
$deployments = data_set($data, 'spots.0.status', 'inactive');
For updating all spots:
$data = $deployments->all();
$deployments = data_set($data, 'spots.*.status', 'inactive');
I have a array with datetime objects .The array lookks like as follows
$advanceresult= array:68 [▼
"contact" => array:1 [▶]
"policyBranch" => ArrayCollection {#38322 ▶}
"assuranceContact" => ArrayCollection {#38337 ▶}
"info" => null
"withSurplusShare" => false
"withSurpassedSurplusShare" => false
"withoutPremiumInvoice" => false
"withoutPremiumInvoiceRange" => array:2 [▼
"start" => DateTime #1577833200 {#38339 ▶}
"end" => DateTime #1609369200 {#38346 ▶}
]
"showPoliciesFromArchivedContacts" => false
]
The withoutPremiumInvoiceRange key value is a datetime object.
My problem is when i encode this array as follows
$advanceresultencode=json_encode($advanceresult);
json_decode($advanceresultencode, true);
and decode it back the datetime objects is looking like as follows
enter code here
"withoutPremiumInvoiceRange" => array:2 [▼
"start" => array:3 [▼
"date" => "2020-01-01 00:00:00.000000"
"timezone_type" => 3
"timezone" => "Europe/Zurich"
]
"end" => array:3 [▶]
]
I need the data to datetime object.Can anyone help me acheiving this.
You can't have the datetime without an extra step. You can change the encode process (more info here: Change output of DateTime in json_encode) but same issue on json_decode.
Here is what you can do on json_decode :
<?php
// Here your json as string
$json = ...;
$jsonDecoded = json_decode($json);
$jsonDecoded['withoutPremiumInvoiceRange']['start'] = DateTime::createFromFormat(
'Y-m-d H:i:s.u',
$jsonDecoded['withoutPremiumInvoiceRange']['start']['date'],
new DateTimeZone($jsonDecoded['withoutPremiumInvoiceRange']['start']['timezone'])
);
So I'm trying to make a function that searches a string in a whole array. But it give me anything... So my array looks like this :
array:1 [▼
"list" => array:2 [▼
"pagination" => array:5 [▶]
"entries" => array:11 [▼
0 => array:1 [▼
"entry" => array:8 [▼
"firstName" => "Doctor"
"lastName" => "Who"
"emailNotificationsEnabled" => true
"telephone" => "0123456789"
"company" => []
"id" => "DW"
"enabled" => true
"email" => "doctorwho#time.lord"
]
]
1 => array:1 [▶]
2 => array:1 [▶]
3 => array:1 [▶]
4 => array:1 [▶]
5 => array:1 [▶]
6 => array:1 [▶]
7 => array:1 [▶]
8 => array:1 [▶]
9 => array:1 [▶]
10 => array:1 [▶]
]
]
]
So for exemple at first I did $key = array_search("doctor", $users); but this gives me nothing. So I thought it was because I have a multidimensional array. So I reduced it to just one array (and I would search in the rest of the original array with a for loop), so now I'm working with this array that I got with $users['list']['entries'][0]
array:1 [▼
"entry" => array:8 [▼
"firstName" => "Doctor"
"lastName" => "Who"
"emailNotificationsEnabled" => true
"telephone" => "0123456789"
"company" => []
"id" => "DW"
"enabled" => true
"email" => "doctorwho#time.lord"
]
]
But $key = array_search("doctor", $users['list']['entries'][0]); still doesn't give me anything (but false).
Does anyone know where is my mistake ? Because I couldn't find a solution of my problem yet and it's been a pretty long time I'm on it... I'm still a beginner in php so maybe I've missed something obvious and i'm sorry if I did.
Thank you in advance !
you are searching for doctor,but value stored in your array is as Doctor. So either search for Doctor as
$key=array_search('Doctor', $users['list']['entries'][0]));
or for case in-sensetive search use
$key=array_search(strtolower('Doctor'), array_map('strtolower', $users['list']['entries'][0]));
Note: as your array is multidimensional, so use loop to search your value