How can access property of variable if difficult properties - php

How can I access property of this type of data: Below data are into $live variable.
$live = =array:17 [▼
"sensex" => {#1130 ▼
+"code": "200"
+"message": "Success"
+"data": {#1131 ▼
+"HIGH": "36551.86"
}
}
"nifty_50" => {#1132 ▶}
"nasdaq" => {#1134 ▶}
I am trying to access value of 'HIGH' property for $live variable in php. I have tried with below code but its give me error:
$live->sensex->data;
Error:
Trying to get property 'sensex' of non-object
EDITED:
I'm trying to access this data structured data which is $live,
$data =
{#1139 ▼
+"chart": {#1138 ▼
+"result": array:1 [▼
0 => {#1135 ▼
+"meta": {#1129 ▶}
+"timestamp": array:195 [▶]
+"indicators": {#1137 ▼
+"quote": array:1 [▼
0 => {#1136 ▼
+"open": array:195 [▶]
+"close": array:195 [▶]
+"high": array:195 [▶]
+"volume": array:195 [▶]
+"low": array:195 [▶]
}
]
}
}
]
+"error": null
}
}
Now How can I access +"open": array:195 directly?

It kind of looks like an associative array, then you will get the get the value by:
$live["sensex"] // etc.

You need to use Array syntax
$live['sensex']->data;

Here $live is an array. Actually, it's an associative array. 'sensex' is a class.
The syntax for getting value from an associative array:
$var_name["key_name"];
For Std class, the syntax is:
$class_name->proparty_name
But we can get proparty value from Std class using associative array syntax. So.
$class_name["proparty_name"] is also Valid.
So for your case, you can use both:
$live["sensex"]->data->HIGH
$live["sensex"]["data"]->HIGH
$live["sensex"]["data"]["HIGH"]

to access an index of an array you need to use ['particular_index_name'].
to access a property of an object you need to use ->particular_property_name.
in your case, $live is an array, sensex is an object and data is also an object.
so. to access the value of HIGH
$live['sensex']->data->HIGH;

Related

How to display pagination links in a blade on Laravel 8?

I need to add pagination, but it seems complicated in my case, because I get data from database with paginate, but then I modify this data and when I call links() method on the blade, I get the following exception
Method Illuminate\Support\Collection::links does not exist.
My code in the Controller method:
$transactionsByLastMonth = Transaction::where('created_at', '>=', Carbon::now()->subDays(30)->toDateTimeString())
->where('user_id', Auth::user()->id)
->with(['user', 'propertyFrom', 'propertyTo', 'paddockFrom', 'paddockTo', 'cattleTypeFrom', 'cattleTypeTo'])
->paginate(10);
$transactionsByDays = collect(TransactionResource::collection($transactionsByLastMonth))
->sortByDesc('created_at')
->groupBy(function($date) {
return Carbon::parse($date['created_at'])->format('d');
});
return view('user.reports.index', compact('transactionsByDays'));
Yes, a pagination limits my data to 10 rows, but due to I'm grouping data by days, my collection modifies itself and I can't use $transactionsByDays->links() method to show pagination.
If see dd($transactionsByDays) , it looks like:
Illuminate\Support\Collection {#1381 ▼
#items: array:3 [▼
"01" => Illuminate\Support\Collection {#1019 ▼
#items: array:7 [▼
0 => array:16 [▶]
1 => array:16 [▶]
2 => array:16 [▶]
3 => array:16 [▶]
4 => array:16 [▶]
5 => array:16 [▶]
6 => array:16 [▶]
]
}
31 => Illuminate\Support\Collection {#1386 ▼
#items: array:2 [▼
0 => array:16 [▶]
1 => array:16 [▶]
]
}
30 => Illuminate\Support\Collection {#1384 ▼
#items: array:1 [▼
0 => array:16 [▶]
]
}
]
}
Therefore I need to paginate all arrays together which inside "01", 31, 30...
How can I do it?
Maybe rewrite code above in the controller somehow?
The main aim is that I need to group data to every day according to my json-resource class.
Any ideas?
I've found a solution gyus. I had to pass also a variable transactionsByLastMonth and use links() method over this.
In the meantime I use foreach on the my blade file over transactionsByDays variable. It's correctly works together cause it uses the same data from database, just in the first case its not filtered and not grouped and in the second one it is.
return view('user.reports.index', compact('transactionsByLastMonth', 'transactionsByDays'));

Laravel sort array according to number of elements in sub array

Is there any laravel collection methold that i dont know of, which would allow me to sort an array based on the number of elements on the sub array?
Illuminate\Support\Collection {#1143 ▼
#items: array:7 [▼
"A" => Illuminate\Support\Collection {#21181 ▼
#items: array:10 [▶]
}
"B" => Illuminate\Support\Collection {#21182 ▼
#items: array:8 [▶]
}
"C" => Illuminate\Support\Collection {#21183 ▼
#items: array:9 [▶]
}
"D" => Illuminate\Support\Collection {#21184 ▼
#items: array:5 [▶]
}
"E" => Illuminate\Support\Collection {#21185 ▼
#items: array:2 [▶]
}
"F" => Illuminate\Support\Collection {#21186 ▼
#items: array:4 [▶]
}
"G" => Illuminate\Support\Collection {#21187 ▼
#items: array:15 [▶]
}
]
}
I could do something like THIS using usort() but I was just wondering if there exists any method within laravel collections, which I yet dont know or may be I am not able to locate it within Laravel Collections.
I don't know if anyone is going to stumble into similar problem, I found a way around it as mentioned in the documentation
I still don't know if this is the perfect way of doing it, but it did the trick for me. I am just posting it such that it might help someone a lot of headache and time.
I would still love to hear other answers and comments on the alternative ways of doing it.
$sorted = $mostWatchedVideosThisWeek->sortByDesc(function ($stats, $key) {
return count($stats);
});
if you searching for usort(), Laravel https://laravel.com/docs/5.8/collections#method-sort work same like usort()
eg:
$full_sorted = $collection_data->sort(function($a ,$b) { //$a first element ,$b second element
if ((count($a) > count($b))) {
return -1;
}else{
return 1;
}
})->values();

Laravel collection: flatten method ignored

Possibly an obvious one, but here it is:
After dd'ing a query result, I have:
$items = DB::table('my_table')->get(['id']);
dd($items);
Which results in:
Collection {#228 ▼
#items: array:1 [▼
0 => {#227 ▼
+"id": 2
}
]
}
Then, when I try to flatten it, it ignores me:
dd($items->flatten());
Resulting in:
Collection {#209 ▼
#items: array:1 [▼
0 => {#227 ▼
+"id": 2
}
]
}
Shouldn't I receive something like the flattened version of the collection?
How can I do it?
Thanks in advance.
You need to check it like
$flattened = $items->flatten();
dd($flattened->all());
// or dd($items->flatten()->all());
Source from official documentation.
If you want to fetch id and completely flatten then use
$items = DB::table('my_table')->pluck('id');
dd($items);
Here is the pluck link.

Laravel 5 get attribute from collection

I have a $location collection that looks like this:
Collection {#225 ▼
#items: array:5 [▼
0 => GoogleAddress {#336 ▼
-id: "ChIJjWwHAP72w0cR44_HJ-bRcJE"
-locationType: "ROOFTOP"
-resultType: array:1 [▶]
-formattedAddress: ""
-streetAddress: null
-intersection: null
-political: ""
-colloquialArea: null
-ward: null
-neighborhood: null
-premise: null
-subpremise: null
-naturalFeature: null
-airport: null
-park: null
-pointOfInterest: null
-establishment: null
-subLocalityLevels: AdminLevelCollection {#339 ▶}
-coordinates: Coordinates {#331 ▶}
-bounds: Bounds {#332 ▶}
-streetNumber: "21"
-streetName: ""
-subLocality: null
-locality: ""
-postalCode: ""
-adminLevels: AdminLevelCollection {#337 ▶}
-country: Country {#335 ▶}
-timezone: null
-providedBy: "google_maps"
}
1 => GoogleAddress {#344 ▶}
2 => GoogleAddress {#352 ▶}
3 => GoogleAddress {#360 ▶}
4 => GoogleAddress {#368 ▶}
]
}
So I am trying to get the formattedAddress like this:
$location[0]->formattedAddress
But I get the following error:
Cannot access private property
Geocoder\Provider\GoogleMaps\Model\GoogleAddress::$formattedAddress
Anyone can help me out here?
It's a collection Do it like this
$location->first()->formattedAddress
The variable is private, meaning you can only access it from within the same class. In this case, the class has a getter method called getFormattedAddress() you can use.
Source: https://github.com/geocoder-php/Geocoder/blob/master/src/Provider/GoogleMaps/Model/GoogleAddress.php#L182
Solution: $location->first()->getFormattedAddress()
And a bit of advice, if you don't understand the private part, you really should have a look at the PHP documentation on visibility: http://php.net/manual/en/language.oop5.visibility.php
First, try to get the first object with $model->first()
If not, try to use mutators:(Here an example)
public function getNameAttribute()
{
return $this->attributes['firstName'];
}

Access element of JSON Object which is in an Array

How can you access a JSON object element that is in an array?
Ideally I would like to know how to do this if the array is of unknown size and also an unknown amount of JSON objects.
In the example below I would like to access id in JSON object 0 and 19.
array:1 [▼
0 => {#411 ▼
+0: {#157 ▶}
+1: {#167 ▶}
+2: {#192 ▶}
+3: {#200 ▶}
+4: {#206 ▶}
+5: {#227 ▶}
+6: {#235 ▶}
+7: {#259 ▶}
+8: {#269 ▶}
+9: {#281 ▶}
+10: {#299 ▶}
+11: {#308 ▶}
+12: {#316 ▶}
+13: {#325 ▶}
+14: {#335 ▶}
+15: {#352 ▶}
+16: {#362 ▶}
+17: {#380 ▶}
+18: {#390 ▶}
+19: {#402 ▼
+"created_at": "Mon Jan 23"
+"id": 823548040000000000
+"id_str": "823548040000000000"
+"text": "blah blah blah blah blah blah blah"
+"truncated": true
+"entities": {#403 ▶}
+"source": "Twitter Web Client"
+"in_reply_to_status_id": null
+"in_reply_to_status_id_str": null
+"in_reply_to_user_id": null
+"in_reply_to_user_id_str": null
+"in_reply_to_screen_name": null
+"user": {#406 ▶}
+"geo": null
+"coordinates": null
+"place": null
+"contributors": null
+"is_quote_status": false
+"retweet_count": 3
+"favorite_count": 8
+"favorited": false
+"retweeted": false
+"possibly_sensitive": false
+"lang": "en"
}
}
]
The top level is an array with one element indexed 0(first lines in your paste). I.e. $var[0].
$var[0] seems to contain an object if I interpret your paste correctly(the curly brace on "0 => {"). Therefor, if you want to access its parts you use ->, in your case $var[0]->0 or $var[0]->19.
Elements 0 and 19 are objects(curly braces). So to access them you do f.ex. $var[0]->0->created_at.
Edit: Accessing numerical object properties isn't as easy as one would wish. But if you cast the object as an array it can be done:
((array) $var[0])[0]->created_at
Explanation: $var[0] is an object, but its properties are numerical. This is where the T_LNUMBER error occurs. So we cast that object as an array: (array) $var[0]. To access element with index 0 in the resulting array it is wrapped in parentheses: ((array) $var[0])[0]. (Without the parentheses("(array) $var[0][0]") it would've been a 2-dimensional array). Now we are at the object with string keys, which can be accessed as usual.
SO question goes through this in more detail.
Do note that the code won't be reusable, it's tailor made for this particular case. So if this situation occurs iin other places you should probably write some function that converts your data from objects to arrays.
If you use json_decode() it will convert the JSON into a PHP variable. Then you can access the elements however you normally would (array indices, etc).
https://secure.php.net/manual/en/function.json-decode.php

Categories