How can I access this string in an stdClass object? - php

I have an stdClass object which looks like this, I am trying to echo out the steamid
stdClass Object
(
[response] => stdClass Object
(
[players] => Array
(
[0] => stdClass Object
(
[steamid] => 76561198039509812
[communityvisibilitystate] => 1
[profilestate] => 1
[personaname] => Mike_Ock_Hurtz
[lastlogoff] => 1506899637
[profileurl] => http://steamcommunity.com/profiles/76561198039509812/
[avatar] => https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg
[avatarmedium] => https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_medium.jpg
[avatarfull] => https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_full.jpg
[personastate] => 0
)
)
)
)
Below is how I am getting the above:
foreach(updateBanList::readFile($file) as $steamprofiles){
$steam = $steamUser->GetPlayerSummariesV2($steamprofiles[0]);
print_r($steam);
$players = $steam->response->players;
}
To access the class so far I am have used
$players = $steam->response->players;
This gets me to the last array
Array
(
[0] => stdClass Object
(
[steamid] => 76561198039509812
[communityvisibilitystate] => 1
[profilestate] => 1
[personaname] => Mike_Ock_Hurtz
[lastlogoff] => 1506899637
[profileurl] => http://steamcommunity.com/profiles/76561198039509812/
[avatar] => https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg
[avatarmedium] => https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_medium.jpg
[avatarfull] => https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_full.jpg
[personastate] => 0
)
)
I am trying to echo out the steamid, and I've tried a few things I know whatever it is i am doing is very simple, but its late in the day and I cannot figure it out.
If I try
$players->steamid;
I get the error
Notice: Trying to get property of non-object
If I try
$players['steamid'];
I get
Notice: Undefined index: steamid
What am I doing wrong?

Try $players[0]->steamid;
Your object is inside an array
And if you are sure you will only get one object element in the array then use
$player = $steam->response->players[0];
$player->steamid; will suffice.

You have to use the array.
$players = $steam->response->players;
$steamid = $players[0]->steamid;
or in one line;
$steamid = $steam->response->players[0]->steamid;
Now you can echo out you steamid:
echo $steamid;
If you have more than one Player in your array you have to loop thou:
$players = $steam->response->players;
$steamids = array();
foreach ($players as $key => $player)
{
$steamids[$key] = $player->steamid;
}
Now you have an array of Steam IDs in $steamids. To echo it you can do:
foreach ($steamids as $key => $steamid)
{
echo "Player " . $key . " has Steam ID:" . $steamid;
}
Notice: Trying to get property of non-object
Now that you understand that the next data type is an array and not an object, it is clear that doing something like $players->steamid; will cause an Error.
Notice: Undefined index: steamid
$players['steamid']; cloud also not work because there is no Key/Index steamid in this array only one Key/Index with the value 0

$players is an indexed array of objects.
Try this:
print_r($players[0]->steamid);
Or this to dump all the array elements:
foreach ($players as $player) {
print_r($player->steamid);
}

$players is array, You should access it's property on array element:
$players[0]->steamid;

Related

How can I put JSON to MySQL with PHP loop?

I have JSON like this (from nested sorting)
[
{"id":13},{"id":14},
{"id":15,
"children":[
{"id":16},{"id":17},{"id":18}
]
},
{"id":19},{"id":20},
{"id":21,
"children":[
{"id":22}
]
}
]
how I PHP loop to put this JSON in MySQL
Thank you.
As with any valid JSON format string, you can use PHP's built-in json_decode to convert it into a parsable object and then loop through those parameters. In this case, from the JSON string you've given (which seems to be an array)
$array = json_decode($string);
foreach ($array as $val) {
//The object $val will be:
"id":13
}
If it's nested, you would do another foreach loop and detect for the property that needs to be looped. For example you could do this in a variety of ways (check for the "children" property, loop through the $val properties and check if it is an array, if it is then loop through that). Inside this foreach loop iteration, you can insert it, or do execute whatever statement you need to get it inside MySQL
Your question is pretty vague on the format and way you want it inserted. I'd suggest showing some code you've tried so other people can help you and know what direction you're going in. (that's probably the reason for the downvote, not mine by the way)
Looping through all the properties of object php
just put your valid json inside json_decode and assign it to a php array as below
//$php_arr = json_decode('YOUR_JSON');
$php_arr = json_decode('[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}]');
/*comment the following 3 lines when done*/
echo "<pre>";
print_r($php_arr);
echo "</pre>";
/*comment the above 3 lines when done*/
output
Array
(
[0] => stdClass Object
(
[id] => 13
)
[1] => stdClass Object
(
[id] => 14
)
[2] => stdClass Object
(
[id] => 15
[children] => Array
(
[0] => stdClass Object
(
[id] => 16
)
[1] => stdClass Object
(
[id] => 17
)
[2] => stdClass Object
(
[id] => 18
)
)
)
[3] => stdClass Object
(
[id] => 19
)
[4] => stdClass Object
(
[id] => 20
)
[5] => stdClass Object
(
[id] => 21
[children] => Array
(
[0] => stdClass Object
(
[id] => 22
)
)
)
)
Now as you have PHP array do what ever you want like
foreach($php_arr as $arr){
if(!isset($arr['children'])){
$q = "insert into tbl(id) values('".$arr['id']."')";
}else{
//your logic
}
}
You need to use json_decode function to decode JSON data. Then use foreach loop to manipulate data.
Try example
$str = '
[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}]
';
$json = json_decode($str);
//var_dump($json);
foreach ($json as $item)
{
//The object $val will be:
echo $item->id."<br />";
//You INSERT query is here
//echo "INSERT INTO table (field) VALUE ($item->id)";
$query = mysqli_query($conn, "INSERT INTO table (field) VALUE ($val->id)");
}

assigining new key value pair to stdclass object in foreach php

Im fetching a pdo object with data from the database. now when i foreach this data I want to add extra key values but this doest work.
foreach ($deliveryCompanies as $k=>$v) {
$k->test = 'test';
}
this returns
Type: ErrorException
Code: 2
Message: Attempt to assign property of non-object
the object looks like this
Array
(
[0] => stdClass Object
(
[delivery_id] => 2
[delivery_location_id] => 34
[delivery_category_id] => 1
)
[1] => stdClass Object
(
[delivery_id] => 4
[delivery_location_id] => 34
[delivery_category_id] => 1
)
)
1
That's because $k is the key, not the value. You need to do $v->test ='test';

Loop through JSON array using PHP

My Code:
$json2 = json_decode($content, true);
$thing = $json2{"reply1"}->{"tokens"};
foreach ($thing as $laa) {
echo $laa->token;
}
Whenever I run this code against my JSON it returns:
PHP Notice: Trying to get property of non-object in /root/backup.php on line 33
PHP Warning: Invalid argument supplied for foreach() in /root/backup.php
All I want to do is loop through the JSON and get one part which is the token for each [token]. (Starting part of JSON)
JSON:
Array
(
[errors] => Array
(
)
[reply] => success
[item] => Array
(
[status] => CURRENT
[messageURI] =>
)
[reply1] => Array
(
[tokens] => Array
(
[0] => Array
(
[token] => 123456
)
[1] => Array
(
[token] => 123456
)
Any help is appreciated.
Thanks.
You're accessing an array. You do this with [], not with {}.
To get at the tokens array, you need $json2['reply1']['tokens'].
Again, you access individual items in this array with [], not ->. Using $laa->token; is going to fail again.
Try the following
$tokens = $json2['reply1']['tokens'];
foreach ($tokens as $token) {
echo $token['token']
}

Retrieving correct record from multidimentional array

I'm having a mental freeze moment. If I have an array in the following format:
$myData = Array
(
[0] => stdClass Object
(
[id] => 1
[busID] => 5
[type] => SMS
[number] => 5128888888
)
[1] => stdClass Object
(
[id] => 2
[busID] => 5
[type] => APP
[number] => 5125555555
)
[2] => stdClass Object
(
[id] => 4
[busID] => 5
[type] => APP
[number] => 5129999988
[verified] => 1
[default] => 0
)
)
And I only have an var for ID of the record, how do I retrieve the rest of the detail for that set.
$myID = 2;
// get number 5125555555 and it's type
echo $myData[][$myID]['number']; // ???
The way you have your data arranged your going to have to loop through your array to identify the object corresponding to $myID.
foreach($myData as $object) if($object->id == $myID) echo $object->number;
The alternative is to arrange your $myData as an associative array with the id field as the key. Then you could access it simply with $myData[$myID]->number.
Actually it's an array that contains StdClass objects , try looping over $myData and access each attribute :
foreach ( $myData as $data )
{
print_r($data->id);
// ...
}
You can avoid loop by using following logic:
<?php
$myID = 2;
$myData = json_decode(json_encode($myData),1); // Convert Object to Array
$id_arr = array_column($myData, 'id'); // Create an array with All Ids
$idx = array_search($myID, $id_arr);
if($idx !== false)
{
echo $myData[$idx]['type'] . ' -- ' . $myData[$idx]['number'];
}
?>
Working Demo
Note: array_column is supported from PHP 5.5.
For lower versions you can use this beautiful library https://github.com/ramsey/array_column/blob/master/src/array_column.php
You can create a custom function to achieve this, you need to pass the array and id whose details you want and the function will return the array with matching id, like below
function detailsById($myData,$id){
foreach($myData as $data){
if($data->id == $id){
return $data;
}
}
}
Just call this function with your array and id..
$data=detailsById($myData,2);
echo "<pre>";print_r($data);
This will give you :
stdClass Object
(
[id] => 2
[busID] => 5
[type] => APP
[number] => 5125555555
)
And further to print 'number' and 'type' use $data array
$data['type'];
$data['number'];

how to get data into an array?

I saved the result of a CURL expression into variable $data. When I print this value using print_r($data), It gives me like that
stdClass Object
(
[zip_codes] => Array
(
[0] => stdClass Object
(
[zip_code] => 10015
[distance] => 0.521
)
[1] => stdClass Object
(
[zip_code] => 10079
[distance] => 0.521
)
[2] => stdClass Object
(
[zip_code] => 10094
[distance] => 0.521
)
I want only zip_code into an array, Please help me how do I get only zip_code into an array.
Thanks
So use array_map():
$result = array_map(function($x)
{
return $x->zip_code
}, $obj->zip_codes);
Try something like :
foreach($data->zip_codes as $zipObj)
{
echo $zipObj->zip_code;
}
This will loop over the zip codes array and output the relevant value.
Try something like this:
First iterate trought the collection of objects an get the zip code property and add it to an array
<?php
$result = array();
$zipCodes = $data->zip_codes;
for($i = 0; $i < sizeOf($zipCodes); $i++){
$result[] = $zipCodes->zip_code;
}
?>
You can use array_map, this function allows you to apply a callback to the array.
$zip_codes = array_map(function($i) { return $i->zip_code; }, $data->zip_codes);

Categories