Accessing an array in an object - php

In PHP I printed return '<pre>'.print_r($getFileId,true).'</pre>'; which is an object. This returns:
<pre>Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
How can I access the last element of the array. Tried end($getFileId) but it returned:
<pre>Array
(
[0] => 1
[1] => 2
[2] => 3
)
</pre>

Your Illuminate object has a method specifically for this purpose:
$getFileId->last();
Please see the docs for more information

Apparently your $getFileId variable is a Collection object, not an array. That's why calling the end function on it does not work, but it doesn't fail either because it implements ArrayAccess.
You could do it in many ways:
end($getFileId->all());
$getFileId->flip()->first();
//beware, this one alters the collection by also removing the last element
$getFileId->pop();
$getFileId->slice($getFileId->count() - 1, 1)->first();
But all these would be just running in circles when you could simply do:
$getFileId->last();

Related

Getting result from DB by laravel DB class which the each index of array is the result id

Guys I'm trying to get the result form my database by laravel 5.5.
If I run this code:
DB::table('comments')->get()
It will return an array which contains stdClasses.
Now I want the key(index) of each stdClass in the array be ID of the stdClass.
I just want to know that laravel has this feature ?
Update:
This is returned Array for example:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 7
....
)
[1] => stdClass Object
(
[id] => 8
....
)
[2] => stdClass Object
(
[id] => 9
....
)
)
)
notice above code. I want 7,8,9 to be instead of 0,1,2 .
Check this, https://laravel.com/docs/5.6/collections#method-pluck
DB::table('comments')->get()->pluck('id');
Edit It seems you want to key your array by id.
There is this method https://laravel.com/docs/5.6/collections#method-keyby ,
so it would be something with the looks of
DB::table('comments')->get()->keyBy('id')->all();
you can use this code for 2 columns (for example 'title' and 'id'):
DB::table('comments')->get()->pluck('title', 'id');
tnx Sérgio Reis but you dont need ->all();
just:
DB::table('comments')->get()->keyBy('id');

Cookie return stdClass Object only

I have and array of few objects. And those objects are instances of different classes.
Suppose
array (
[0] => Car Object(
[id] => 6
[name] => Texi 1
)
[1] => Bed Object(
[id] => 40
[name] => Sleeping Bed
)
)
Now I am saving this to cookie, and before saving I am using using json_encode on it.
While retrieving If I use json_decode($data), I am getting an array of stanadrd objects, and if I use json_decode($data, true), then I am getting only array of arrays !!!
So instead of stdClass objects how can I get actual objects ? is it possible ?
I have tried serialize(json_decode($data, true)); but in vain. Thanks in advance for help.
use serialize($data) instead and unserialize($data) to retrieve the original data.
don't use json_encode before serializing as it will turn the classes into StdObject or Arrays.

How to grab value from array

I am pulling an array from my DB that is saved in this format:
[categories] => [
{"category":"Exit Sign"},
{"category":"Leaving"},
{"category":"Illuminated"},
{"category":"Sign"},
{"category":"Red"},
{"category":"Warning Sign"},
{"category":"Above"}
]
How can I loop through each {} and get the category?
Edit: I have attempted passing each JSON array from my DB through json_decode() but I am getting the following error "json_decode() expects parameter 1 to be string, array given..." Any idea what would cause this?
Edit 2: Here is the var_dump output for just one row in my DB:
array(1) {
["categories"]=>
string(845) "[{"category":"Built Structure"},{"category":"The Americas"},{"category":"Sky"},{"category":"New York City"},{"category":"Manhattan - New York City"},{"category":"USA"},{"category":"History"},{"category":"Suspension Bridge"},{"category":"Brooklyn - New York"},{"category":"Brooklyn Bridge"},{"category":"Scenics"},{"category":"Skyscraper"},{"category":"River"},{"category":"Downtown District"},{"category":"East River"},{"category":"Cityscape"},{"category":"Bridge - Man Made Structure"},{"category":"City"},{"category":"Lighting Equipment"},{"category":"Arch"},{"category":"Urban Skyline"},{"category":"Architecture"},{"category":"Sunset"},{"category":"Night"},{"category":"Modern"},{"category":"Urban Scene"},{"category":"Tower"},{"category":"Famous Place"},{"category":"Gate"},{"category":"Outdoors"},{"category":"East"},{"category":"Travel"}]"
}
Got it! I had to pass $array['categories'] into json_decode and then it worked properly. Thanks everyone for your help!
Well, So you are new to this world. You are welcome.
Let your array value is names as $json. This value is a json format, so for access this value you need to decode them. You need to use a function called json_decode, which has two parameter, the first one is string where you pass your variable json, an second one is bool where you pass true or false.
You have to pass when you want your array as associative not object. Here i ignore the second option, so my return array is object.
After decoding your json string you have an array, now you have to use a loop foreach to browse all the elements of the array. As you can see in the resultant array below, the array is multi-dimensional so after applying a foreach loop you just reach the first depth. For getting the value of category you should need to use -> after $val which is the first depth array.
$json = '[{"category":"Exit Sign"},{"category":"Leaving"},{"category":"Illuminated"},{"category":"Sign"},{"category":"Red"},{"category":"Warning Sign"},{"category":"Above"}]';
$arr = json_decode($json); //Also you can pass $yourArr['categories'];
foreach($arr as $val){
echo $val->category."<br/>";
}
After decoding your array looks like:
Array
(
[0] => stdClass Object
(
[category] => Exit Sign
)
[1] => stdClass Object
(
[category] => Leaving
)
[2] => stdClass Object
(
[category] => Illuminated
)
[3] => stdClass Object
(
[category] => Sign
)
[4] => stdClass Object
(
[category] => Red
)
[5] => stdClass Object
(
[category] => Warning Sign
)
[6] => stdClass Object
(
[category] => Above
)
)
Result:
Exit Sign
Leaving
Illuminated
Sign
Red
Warning Sign
Above

php: trying to call data from an object

I am trying to get specific data set from the object but unable to find out why I cannot call the number in my assignment. This is it as follows:
$teir = $league->data->summonerLeagues->0->teir;
First of all this is calling the data from the league which is set and so that yo can see what the data looks like here it is:
stdClass Object
(
[data] => stdClass Object
(
[summonerLeagues] => Array
(
[0] => stdClass Object
(
[queue] => RANKED_SOLO_5x5
[name] => Dr. Mundo's Crushers
[tier] => BRONZE
[requestorsRank] => III
[entries] => Array
at this point I am trying to assign the variable $teir to teir in the object but they use 0 in the object and the way I am calling it must be the issue.....
Any suggestions?
Array access is with brackets, while object properties are accessed with ->:
$tier = $league->data->summonerLeagues[0]->tier; // Fixed typo per #MikePurcell's comment

Retrieve value from a multi-dimensional array in PHP

I have a multidim array that I can view using print_r($users):
Array
(
[0] => stdClass Object
(
[username] => crustacea
[created_on] => 2010-08-07 19:54:32
[active] => 1
)
)
I can also use print_r($users[0]). Since there's only one member in $users, the output looks somewhat the same.
I can't see how to retrieve the value crustacea. echo $users[0]['username']; doesn't do it. Examples I can find are echo $users['name_of_array']['username']; -- but I don't have a name of array to work with. How do I do it?
$user[0] is not an array but an object as indicated by [0] => stdClass Object.
echo $users[0]->username;
$user[0] is object and not an array. You can access your value by doing
$users[0]->username;
Or you could cast/convert your object into an array like
((array)$users[0])['username'];

Categories