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
Related
I've upgraded our Laravel application from Laravel 5.2 to 5.3 and got a warning message from Laravel side
The Query Builder returns collections, instead of plain arrays, in
Laravel 5.3. You will need to upgrade your code to use collections or
chain the all() method onto your query to return a plain array.
Thats means fluent query builder now returns
Illuminate\Support\Collection instances instead of plain arrays. This
brings consistency to the result types returned by the fluent query
builder and Eloquent.
You can standard this by below example
Laravel 5.2
$users = DB::table('users')->select('id','first_name')->limit(10)->get();
dd($users);
Result :
==========
array:10 [▼
0 => {#1423 ▼
+"id": 12
+"first_name": "John"
}
1 => {#1424 ▶}
2 => {#1425 ▶}
3 => {#1426 ▶}
4 => {#1427 ▶}
5 => {#1428 ▶}
6 => {#1429 ▶}
7 => {#1430 ▶}
8 => {#1431 ▶}
9 => {#1432 ▶}
]
Laravel 5.3
$users = DB::table('users')->select('id','first_name')->limit(10)->get();
dd($users);
Result :
==========
Collection {#1428 ▼
#items: array:10 [▼
0 => {#1430 ▼
+"id": 12
+"first_name": "John"
}
1 => {#1431 ▶}
2 => {#1432 ▶}
3 => {#1433 ▶}
4 => {#1434 ▶}
5 => {#1435 ▶}
6 => {#1436 ▶}
7 => {#1437 ▶}
8 => {#1438 ▶}
9 => {#1439 ▶}
]
}
When I am trying to access data by $users[0]->first_name getting same result thats is correct.
That creates confusion for me.. What is the actual difference here and what will be the impact on our application?
Laravel collections implement "Arrayable" which means they inherit all of the same functionality as normal arrays but also have the additional functionality that collections provide, so you will not get any issues accessing at index.
If you want to convert it back to a normal array, you could do ->toArray()
$users = DB::table('users')->select('id','first_name')->limit(10)->get()->toArray();
I was worried about Array and Collection elements and lastly i know
That Collection class holds the collection elements in a protected
property called $items (as you could see from your dump protected
'items' =>), which is of type array. The class also implements an
interface called IteratorAggregate, which basically means it allows
any variable of that type to be iterated using a foreach statement.
So in short Collection is an iterable object that can be treated as an array, but is better than an array because if offers extra methods that allow you to manipulate the items from the collection. You can check the Collection API to see a complete list of available methods.
Ref : In a Laravel 5 Collection how do you return an array of objects instead of an array of arrays?
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;
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'];
}
Hi everyone i'm looking for a way to get a value in a variable but i'm stuck with an array like
$prixArrayArticle = $article->getArticlePlateforme()->getValues();
dump($prixArrayArticle);
gives me
ReassortController.php on line 1149:
array:1 [▼
0 => ArticlePlateforme {#1469 ▼
-article: Article {#1321 ▶}
-plateforme: Plateforme {#1051 ▶}
-codeProduitGv: "365717 "
-fournisseurCommun: FournisseurAchatsAdherents {#1445 ▶}
-referenceFournisseur: "100050 "
-minimumCommande: 1
-colisage: 12
-qtePalette: 12
-decolisable: true
-stock: 182
-dateCreation: DateTime {#1326 ▶}
-present: true
-articleSubstitution: null
-prix: PersistentCollection {#1430 ▼
-snapshot: array:1 [ …1]
-owner: ArticlePlateforme {#1469}
-association: array:19 [ …19]
-em: EntityManager {#137 …11}
-backRefFieldName: null
-typeClass: ClassMetadata {#1261 …}
-isDirty: false
#collection: ArrayCollection {#1439 ▼
-elements: array:1 [▼
0 => Prix {#1412 ▼
-id: 4175988
-dateDebut: DateTime {#1325 ▶}
-dateFin: DateTime {#1324 ▶}
-prixNet: "4.970"
-prixVenteConseille: null
-quantiteMinimum: null
-type: "permanent"
-numeroPromo: null
-offreComplementaire: false
-minimumCommande: 0
-colisage: 0
-invisible: null
-present: true
}
]
}
#initialized: true
}
-prixPromo: PersistentCollection {#1399 ▶}
}
]
and this
$article = $requeteArticle->getQuery()->getSingleResult();
give me this
ReassortController.php on line 1129:
Article {#769 ▼
-id: 1000940
-nom: "FILM DE PAILLAGE FRAISES FRESAFILM 1M40X10M"
-nomCourt: "FILM PAILLAGE FRAISES 1M40X10M"
-gamme: 5
-ecoContribution: "0.00"
-ecoMobilier: "0.00"
-quantiteAchat: "1.00"
-nombreUvParUa: "1.00"
-prixVenteConseille: "9.50"
-present: true
-tauxTva: TauxTva {#908 ▶}
-marque: null
-articleGencod: PersistentCollection {#1007 ▶}
-sousFamille: SousFamille {#635 ▶}
-articlePlateforme: PersistentCollection {#960 ▶}
-uniteAchat: UniteConditionnement {#833 ▶}
-uniteVente: UniteConditionnement {#833 ▶}
}
how can i get the name value for example in a variable because the array only have one index and i really don't know how to get a value with this array
Assuming that the properties are protected and that you have getters for them in your ArticlePlateforme and Article class, you should be able to get them like that:
$articleName = $prixArrayArticle[0]->getArticle()->getNom();
Otherwise, if the properties are public, you could simply get them like:
$articleName = $prixArrayArticle[0]->article->nom;
I have this collection:
Collection {#604 ▼
#items: array:4 [▼
0 => CarsMark {#596 ▶}
1 => CarsMark {#594 ▶}
2 => CarsMark {#594 ▶}
3 => CarsMark {#595 ▶}
]
}
As you can see there is two the same items (594). How can i retrieve all items from with collection without the same items?
Use the collection's unique method:
$unique = $collection->unique();