problems with JSON Decode & strings - php

having a bit of an issue here. I'm passing data over an AJAX command to my php script. The data travels across fine.
Print_r
Array
( [0] => stdClass Object
( [Loc] => Main Door
[Module] => O2
[Dect] => O2
[GasDec] => O2
[ScB4] =>
[ScA4] =>
[A1] =>
[A2] =>
[CalGas] =>
[CalGasA] =>
[Factor] =>
[ZB4] =>
[ZA4] =>
[CalB4] =>
[CalA4] =>
[CHNoID] => 5
[JobID] => 3 )
)
I can use The following method just fine but when i use option two it doesn't like it due to this error message:
Catchable fatal error: Object of class stdClass could not be converted to string
Methods
//Method one
echo "JobID: " . $comm[0]->JobID; // result: 3
//Method two
echo "JobID: '$comm[0]->JobID'"; // get error message
The reason im using method two is so I can pass the information into mysql. If anyone knows something i'm missing or it can't be done or even a easier way. please say.
Thanks.
EDIT
Query
$sql = "INSERT INTO
calinfo (Sbefore, Safter, A1, A2, CalGas, Factor, Zbefore, Zafter, Cbefore, Cafter, SysInfoID)
VALUES
('$comm[$i]->ScB4', '$comm[$i]->ScA4', '$comm[$i]->A1', '$comm[$i]->A2', '$comm[$i]->CalGasA', '$comm[$i]->Factor', '$comm[$i]->ZB4', '$comm[$i]->ZA4', '$comm[$i]->CalB4', '$comm[$i]->CalA4', '$comm[$i]->CHNoID');";
$sql .= "UPDATE
jobs
SET
CompletedBy = $tech
WHERE JobID = '$comm[$i]->JobID';"; //<-- when i try the method of "WHERE JobID = ".$comm[$i]->JobID.";"; it doesnt like it...

You may need to do as
echo "JobID: '{$comm[0]->JobID}'";
So in the query u can use it as where some_col = '{$comm[0]->JobID}'

Try like this
$sql .= "UPDATE
jobs
SET
CompletedBy = $tech
WHERE JobID = '".$comm[$i]->JobID."'";

As the error message saies, the return cannot be converted to fit into a string directly.
echo sprintf( "JobID: '%s'",$comm[0]->JobID);
or
echo "JobID: '{$comm[0]->JobID}'";
or
echo "JobID: '" . $comm[0]->JobID . "'";
should do the trick

Simple double quotes won't interpolate complex combinations like this. You need to use curly braces to achieve this, e.g. echo "JobID: {$comm[0]->JobID}";.
You could however also use printf, e.g. printf("JobID: %s", $comm[0]->JobID);.

Related

What is wrong with how I create this variable for summoner from the Riot API? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
enter code hereThe error this code returns is
"Trying to get property of non-object" or "Message: Undefined property: stdClass::$name".
The variable $summoner is what does not work. Assume the variables sID, $lcaseregion and $APIkey (etc.) are all properly set.
<?php
$summonerURL = "https://$lcaseRegion.api.pvp.net/api/lol/$lcaseRegion/v1.4/summoner/" . $sID . "?api_key=9" . $APIkey;
$responseSummoner = #file_get_contents($summonerURL);
$summoner = #json_decode($responseSummoner);
echo print_r($summoner); //this works and prints things
echo $summoner->name; //this does not work
echo $summoner->profileIconId; //this also does not work.
//please find print_r results below...
?>
print_r results;
stdClass Object ( [41245441] => stdClass Object ( [id] => 41245441 [name] => Bubbalubagus [profileIconId] => 558 [revisionDate] => 1488775287000 [summonerLevel] => 30 ) )
Any other advice and tips you can give me on how the arrays work would also be appreciated.
Try this:
$summoners = #json_decode($responseSummoner);
foreach($summoners as $summoner){
echo $summoner->name;
echo $summoner->profileIconId;
}
As it was pointed out already, you need to loop through the found summoners (although it is only one)
//EDIT: saw an object that wasnt there, this works now

PHP - Undefined offset (0) even though it holds a value

I'm trying to work in a CodeIgniter environment and while trying to collect and gather some information into variables I'm getting some PHP NOTICE errors that don't seem right.
Here's the chunk of code where the error(s) occur:
if (empty($events['user'][$user_id])) {
unset($events['user'][$user_id]);
} else {
foreach ($events['user'][$user_id] as $event) {
$events['user'][$user_id]['events']['event_id'] = $event_id = $event['event_id'];
$events['user'][$user_id]['event']['date'] = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $events['user'][$user_id]['event']['date'][0]['date'];
$events['user'][$user_id]['event']['request_title'] = $event['request_title'];
$events['user'][$user_id]['event']['event_status_text'][] = $this->events_model->getEventStatusFromSectionStatuses($event_id);
$request_data = $this->requests_model->getRequestInfo($event['request_id']);
$events['user'][$user_id]['event']['ministry'] = $this->ministries_model->getMinistryTitle($request_data[0]['requesting_ministry']);
// more stuff will go here...
}
$content_data['event_status_text'] = $events['user'][$user_id]['event_status_text'];
$content_data['events'] = $events['user'][$user_id]['complete_events'];
$content_data['totals'] = $events['user'][$user_id]['totals'];
$content_data['updated_events'] = $events['user'][$user_id]['updated_events'];
}
The specific line of the first error is the third line inside the foreach loop that ends with ['date'][0]['date']. It's the [0] that PHP is telling me is undefined. However, if I echo that exact same variable like this:
echo $events['user'][$user_id]['event']['date'][0]['date'];
...it outputs a value as would be expected, which also tells me that the [0] is NOT undefined after all. I'm not actually changing the variable. The only difference is that I'm echoing it instead of assigning it to another variable.
If I use # to ignore it in here, it happens again a few lines later on the line ending with getMinistryTitle($request_data[0]['requesting_ministry']).
Can you see what I'm doing wrong? Let me know if you need to see more of the code.
Here's the getEventDates() code as requested (note this is not my code):
function getEventDates($event_id)
{
$sql = "SELECT date FROM `event_dates` WHERE event_id=? ORDER BY date";
$res = $this->db->query($sql, array($event_id));
return $res->result_array();
}
if I print out $this->events_model->getEventDates($event_id) I get the following:
Array
(
[0] => Array
(
[date] => 2014-05-01
)
[1] => Array
(
[date] => 2014-05-08
)
[2] => Array
(
[date] => 2014-05-15
)
[3] => Array
(
[date] => 2014-05-22
)
[4] => Array
(
[date] => 2014-05-29
)
[5] => Array
(
[date] => 2014-06-05
)
[6] => Array
(
[date] => 2014-06-12
)
)
Hmmm... is it possible that this error is happening because there isn't a direct value contained in [0], but rather another array level? Please note that I did not structure this output. Someone else coded this and it's just my job to come in and work with it.
Without seeing the rest of your code this is confusing:
$events['user'][$user_id]['event']['date'] = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $events['user'][$user_id]['event']['date'][0]['date'];
Why would you be setting $events['user'][$user_id]['event']['date'] in one line and then in the next overriding it again?
My best advice would be to set the first assignment in a variable independent of the array, and then calling that variable for the data:
$event_dates_temp = $this->events_model->getEventDates($event_id);
$events['user'][$user_id]['event']['date'] = $event_dates_temp[0];
And perhaps adding a conditional check to ensure you are setting things that exist:
$event_dates_temp = $this->events_model->getEventDates($event_id);
if (array_key_exists(0, $event_dates_temp)) {
$events['user'][$user_id]['event']['date'] = $event_dates_temp[0];
}
Also, it’s unclear at what point you are doing this:
echo $events['user'][$user_id]['event']['date'][0]['date'];
And what is the output when you do dump like this:
echo '<pre>';
print_r($events['user'][$user_id]['event']['date']);
echo '</pre>';
It happens when you are trying to access a value which is not set for that index, please read this link for more information.
There are two options available:
Ignore these notices by telling the PHP error_reporting to not show notices error_reporting(E_ALL ^ E_NOTICE); but it is a good practice to fix this error by adding a check if a value exists.
Fix the values by isset function to see if the value/index contains any data.
If You hide notice set error_reporting(E_ALL ^ E_NOTICE);
Solution is use isset() to solved this issue.

PHP Fatal error: Cannot use string offset as an array

Facing a weird situation with arrays..
I am using LinkedIn API to get profile info which returns data in two formats..
If user has just one educational item
educations=>education=>school-name
educations=>education=>date
...
If more than one education item
educations=>education=>0=>school-name
educations=>education=>0=>date
...
educations=>education=>1=>school-name
educations=>education=>1=>date
...
Now I am trying to make it consistent and convert
educations=>education=>school-name
to
educations=>education=>0=>school-name
But getting error in code that i believe should work
if(empty($educations['education'][0]['school-name']))
{
$temp = array();
$temp['education'][0]=$educations['education'];
$educations = $temp;
}
This fails for "just one educational item", generates error on the first line for (isset,is_array and empty)
PHP Fatal error: Cannot use string offset as an array in ...
print_r returns
[educations] => Array
(
[education] => Array
(
[id] => 109142639
[school-name] => St. Fidelis College
[end-date] => Array
(
[year] => 2009
)
)
)
Usually you'd write the assignment like this:
$temp = array(
"education" => array($educations['education'])
);
To avoid any issues with indexes. This might also fix yours.
If you're unsure about the contents of $educations['education'][0]['school-name'] you can simply check each part:
if(isset($educations['education'], $educations['education'][0], $educations['education'][0]['school-name']))
This works because isset doesn't behave like a normal function. It takes multiple arguments in a lazy manner.
You want:
if(array_key_exists('school-name',$educations['education']))
{
$educations['education'] = array($educations['education']);
}
Today I experienced the same problem in my application. Fatal error: Cannot use string offset as an array in /home/servers/bf4c/bf4c.php on line 2447
line 2447
if (!isset($time_played[$player]["started"])) {
$time_played[$player]["started"] = $time;
}
$time_played was overwritten elsewhere and defined as a string. So make sure you do use unique variable names.
Here's a tip if you're running through a loop, and it breaks:
if( $myArray != "" ){
// Do your code here
echo $myArray['some_id'];
}

PHP in_array not returning expected results

When I attempt to determine if a user is in an array of users, for some reason it is only returning true when the user is in the 0th position.
For the life of me I cannot figure out what I am doing wrong.
This does not echo "True"
echo $usersign; // RDW
print_r($these_analysts[0]); // Array ( [0] => JKB [1] => RDW )
if(in_array($usersign,$these_analysts[0])){
echo "True";
}
This echoes "True"
echo $usersign; // RDW
print_r($these_analysts[0]); // Array ( [0] => RDW [1] => CLM )
if(in_array($usersign,$these_analysts[1])){
echo "True";
}
EDIT:
vardump gives a much more comprehensive view of the array, whereas print_r did show the trailing spaces, it didn't catch my eye.
For some reason the first element of each array was giving string3, and all others were giving string4.
You have a lot of syntax errors.
When you use strings, it is always better prace to put strings in single or double quotes. It doesn't matter which one (as far as speed is concerned).
Also, you need commas between the elements.
I entered the following code and it works.
$usersign = 'RDW';
$these_analysts[0] = array( 'JKB', 'RDW' );
print_r( $these_analysts );
if(in_array($usersign,$these_analysts[0])) echo "True";
Try:
$usersign = 'RDW';
$these_analysts[1] = Array ( 0 => 'RDW', 1 => 'CLM' );
if(in_array($usersign,$these_analysts[1])){
echo "True";
}
That should work.
This is happening (at least in my testing) if you specify RDW as a constant without defining these constants before using them. If you put your initials in double-quotes (i.e. use explicit strings) then everything works fine. If you want to use them as constants, then define these constants first:
define("RDW","RDW");
define("JKB","JKB");
And then your code works as expected again.
You're missing ; on half of your lines, you're using base strings instead of " around them, and your Array syntax is invalid (should be Array("JKB","RDW");). Maybe if these are fixed it might have a chance of working.
You have punctuation errors:
$these_analysts[0] = Array ( [0] => JKB [1] => RDW )
should be
$these_analysts = Array ( 0 => "JKB", 1 => "RDW" );
*This is the actual way you need to do *
$usersign = 'RDW';
$these_analysts = array ( 0 => 'RDW', 1 => 'CLM' );
if(in_array($usersign,$these_analysts)){
echo "True";
}

Retrieve value from a Json Array

I'm having difficulty in retrieving values from a Json array. I have a Json dataset that has been created using json_encode. This is how it appears after using json_decode and displaying using print_r:
Array ( [0] => stdClass Object ( [postID] => 1961 [postTitle] => Kiss My Fairy [previewThumb] => 2011/09/Kiss-My-Fairy-Ibiza-essentialibiza-2011_feature.jpg [blogContent] => Ibiza has always had a flair for the extravagant, inhibitions are checked in at the airport when the floods of tourists arrive and the locals have embraced a freedom of partying that has turned the quiet Mediterranean island into the Mecca... ) ) a_post_data_array = 1
The code that achieves this is as follows:
$post_data_URL = "http://myurl.com/news/scrape/facebook-like-chart-ID.php?post_name=kiss-my-fairy";
$post_data_response = file_get_contents($post_data_URL);
$a_post_data_array=json_decode($post_data_response);
I now simply need to retrieve some of the values from this array to use as variables. The array will only ever have 1 set of values. I'm using the following code but it isn't working.
echo "**** -- " . $a_post_data_array[post_title] . "<br>";
Can anyone please help? I'm sorry this is so basic. I've been searching online but can't find any examples of this.
There are multiple issues with your code:
First you should instruct json_decode to give you a pure array with $data = json_decode($response, TRUE);
Then the result array is a list, and you have to access the first element as $data[0]
The entry you want to access has the key postTitle, not post_title as your example code showed. (And unless that's a predefined constant won't work.)
And you need to put those array keys in quotes, like print $data[0]["postTitle"];
Turn up your error_reporting level for some development help.
echo "** -- " . $a_post_data_array[0]['post_title'];
try this PHP code:
//$post_data_response = file_get_contents("https://raw.github.com/gist/1245028/80e690bcbe6f1c5b46676547fbd396ebba97339b/Person_John.json");
//$PersonObject = json_decode($post_data_response);
// Get Person Object from JSON Source
$PersonObject = json_decode('{"ID":"39CA2939-38C0-4C4E-AE6C-CFA5172B8CEB","lastname":"Doe","firstname":"John","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","snowboard"]}],"address":{}}');
// Get data from Object
echo "Person ID => $PersonObject->ID<br>";
echo "Person Name => $PersonObject->firstname<br>";
echo "Person Lastname => $PersonObject->lastname<br>";
echo "Person Age => $PersonObject->age<br>";
echo "Person Hobbies => " . $PersonObject->hobbies[0] . "<br>";

Categories