im requesting information from the instagram api in php like this:
<?php $relation = $instagram->get('users/'.$item->id.'/relationship');
..
which return this json data array for me:
object(stdClass)#58(2){
[
"meta"
]=>object(stdClass)#59(1){
[
"code"
]=>int(200)
}[
"data"
]=>object(stdClass)#60(3){
[
"outgoing_status"
]=>string(7)"follows"[
"target_user_is_private"
]=>bool(true)[
"incoming_status"
]=>string(4)"none"
}
}
note: i used var_dump($relation) to bring this out
what I'm trying to do is loop through this array and display the outgoing status and the incoming status i.e
loop(json-array){
echo outgoing_status;
echo incoming_status;
}
thank you very much..
You have an object (instance of stdClass, the generic object), not an array.
$outgoing_status = $response->data->outgoing_status;
$incoming_status = $response->data->incoming_status;
As a side note, use json_decode($json, TRUE) to return the data as an associative array instead of an object.
Related
So I have a class "File" that has a field "file_history" in JSON, and in my CRUD operations on Laravel I'd like to append some JSON values to this field, for instance, when I'm creating my File object in my database, I first have {"created_at": "2022-07-18"} in my file_history field.
And then if I update my object I would now have:
{
"created_at": "2022-07-18"
},
{
"updated_at": "2022-07-08"
}
So I first thought about transforming my initial JSON values from my previous CRUD operations on the object into an array, append the new JSON values to this array, and then encode my array again into JSON. This is the code I wrote:
public function update(Request $request, String $uuid)
{
$file = File::find($uuid);
$json_data = array(
"updated_at" => Carbon::now()
);
$file_history = json_decode($file->file_history, true);
$file_history = array_push($file_history, $json_data);
$file->file_history = json_encode($file_history);
$file->update($request->all());
return $file;
}
But using that code, I now have "2" in my database in my file_history field... I don't have JSON or anything else, just this 2 even if my field is categorized as JSON. Any idea why and how to fix this?
Thanks
You have "2" in your database, because array_push function returns the new number of elements in the array.
So your code shoud be like this:
$file_history = json_decode($file->file_history, true);
array_push($file_history, $json_data);
$file->file_history = json_encode($file_history);
I have a PHP plain array which I need converted to it's original entity. Example:
class Contact
{
protected $name;
getName(){}
setName(){}
}
This gets send back and forth via an API, and at some point I have that contact as an array element:
$example = ['name'=>'Foo Bar'];
I would like that back as an Contact class. At the moment, I can do that via a serialize/deserialize, but I'm hoping there is a more efficient method for this:
foreach($examples as $example) {
$temp = $this->serializer->serialize($example, 'json');
$contact = $this->serializer->deserialize($temp, Contact::class, 'json');
}
This works, and $contact is now instance of Contact. But I have to perform this on 100 items in one go, possibly more.
I'm thinking of creating a toObject() method, which assigns the values by keys, but that doesn't seem a lot better.
Is there way to accomplish this without writing my own logic or doing the extra serializing step?
Please note: I get the data array, I cant get the 'raw' json. Please take that 'as is'.
Denormalizing from raw JSON input
If you are getting the information from an API, you could probably do away with the JSON conversion and deal with the input directly, since most likely the API is not sending you a native array, but a JSON you are converting to an array at some point
The Serializer component can handle arrays as well, directly.
Assuming an input JSON like this:
$data = '[
{
"name": "Mary"
},
{
"name": "Jane",
},
{
"name": "Alice"
}
]';
You could call deserialize() saying you expect Contact[] in your input data:
$contacts = $serializer->deserialize($data, Contact::class . '[]', 'json');
This would get you a Contact array in one single step.
Denormalizing from array to object
If for some reason the original input is not available or not readily unserializable and you really need to convert from an array to an object one by one, and your objects have setters like the ones you show in your question; you could simply use the GetSetMethodNormalizer (one of the normalizers than the Serializer component uses internally).
E.g.:
$contacts = [
['name' => 'Mary'],
['name' => 'Jane'],
['name' => 'Alice'],
];
$normalizer = new GetSetMethodNormalizer();
foreach($contacts as $arrayContact){
$contact = $normalizer->denormalize(Contact::class, $arrayContact);
// do something with $contact;
}
I'm trying to get Count of a table called TestRunList that has the foreign key the same as another table called Testrun meaning i want to get count of how many testrunlist that single testrun has in the same page i did a forloop to get testrun id for each testrunlist but it didn't seem to work i get this error
Cannot use object of type stdClass as array
heres my Code in the controller
$data = DB::table('TestRun')->get();
$runs=array();
for ($i=0;$i<sizeof($data);$i++)
{
$testrunID=$data[$i]['TestRunID'];
$Testrunlist=TestRunList::where('test_run_id',$testrunID)->count();
$runs[$i]=[
'Countruns'=>$Testrunlist
];
}
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
$data is a Collection, you can't access using array syntax
$data = DB::table('TestRun')->get();
$runs = [];
$data->each(function ($row) use ($runs) {
$runs[] = [
'Countruns' => TestRunList::where('test_run_id',$row-> TestRunID)->count()
];
});
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
Always use
print_r($data);
if it's object run echo $data->username if array run echo $data['username'];
So you know what type of data you're dealing with.
I am absolutely new in PHP and moreover in Laravel framework (I don't know if Laravel provides some utility class for this kind of tasks). I came from Java.
So I have the following problem:
Into a class I perform a call to a REST web service, something like this:
$response = $client->get('http://localhost:8080/Extranet/login',
[
'auth' => [
'dummy#gmail.com',
'pswd'
]
]);
$dettagliLogin = json_decode($response->getBody());
\Log::info('response: '.(json_encode($dettagliLogin)));
$response->getBody() contains the returned JSON object, this is the output of the previous \Log::info():
{
"id":5,
"userName":"Dummy User",
"email":"dummy#gmail.com",
"enabled":true
}
So I have the following problems:
1) What exactly returns the json_decode() function? I really can't understand because PHP is not strongly typed and I have not a declared return type.
This is the method signature:
function json_decode($json, $assoc = false, $depth = 512, $options = 0)
and in the related doc it says #return mixed. What exactly means "mixed"?
2) Anyway the main problem is: I have to use the content of the previous returned JSON object and put these value into the related field of an array like this:
$attributes = array(
'id' => HERE THE id FIELD VALUE OF MY JSON OBJECT,
'username' => HERE THE email FIELD VALUE OF MY JSON OBJECT',
'name' => HERE THE userName FIELD VALUE OF MY JSON OBJECT,
);
So I think that I have to parse the value of the $response->getBody() or of the json_decode($response->getBody()) to obtain these values. But how exactly can I do it? What is the neater way to do it? Does the Laravel framework provide some utility to do it?
For better understanding, let's first describe - what's JSON?
It's a way of representing objects (arrays, objects, etc) in a string.
1) What exactly returns the json_decode() function? I really can't
understand because PHP is not strongly typed and I have not a declared
return type. This is the method signature:
function json_decode($json, $assoc = false, $depth = 512, $options =
0) and in the related doc it says #return mixed. What exatly means
mixed?
json_deocde converts the JSON string into the original "structure" it represent.
#return mixed means that the returned value of json_decode can be any type of variable. If the JSON represent an array - it would be an array type, if it represent an object - it would be an object type.
2) Anyway the main problem is: I have to use the content of the
previous returned JSON object and put these value into the related
field of an array like this:
$attributes = array(
'id' => HERE THE id FIELD VALUE OF MY JSON OBJECT,
'username' => HERE THE email FIELD VALUE OF MY JSON OBJECT',
'name' => HERE THE userName FIELD VALUE OF MY JSON OBJECT,
);
In order to make sure which type of variable your JSON represent, you can use var_dump(json_decode($json));. Anyway, it's a class object.
Therefore:
$object = json_decode($json);
$attributes = array(
'id' => $object->id,
'username' => $object->email,
'name' => $object->userName,
);
If you json string is an object (not an array) it will return an object (of type stdClass). Mixed means it can be multiple things, so if it was a json array, you'd get an array.
Best thing to do is use json_decode, and then var_dump (or var_export) to see what you actually get.
I have a proper .json physical file and i read it from PHP by parsing it.
Let's say the sales.json contains:
{
"custid" : "7761",
"items" : [
{
"itemcode" : "A11231G",
"suppliers" : [
{
"id" : "s10001",
"name" : "Benny & John",
},
{
"id" : "s10004",
"name" : "Colorado Dimension",
}
]
}
]
}
Then i consume it from PHP:
$sales = json_decode( file_get_contents("store/sales.json"), true );
There is no problem and $sales is already become an Array which is ok.
Now for some reason, i want to feed that json_decode() function with an PHP Array (instead of the .json physical file).
I know it is the dumb way that i am actually doing like converting, Array -> json -> Array, which is finally Array to Array.
But for whatever reason i have,
Even if i have a PHP Array() with the correct structure, if i use json_encode($phpArray), then to feed as json_decode( json_encode($phpArray), true ), will it give the exact object like i get from json_decode("sales.json") file?
(or) how can i feed the json_decode function with a PHP Array() object i have?
Actually, json_decode returns a STD object, not an array. To get an array from a JSON string you need to use json_decode($string, true).