I'm not too sure how to fix an issue i've encountered.
$Xsummoner_fetcher = mysqli_fetch_row($Xcheck_sql);
$summonerName = $summoner[2];
$result = file_get_contents('$url');
$summoner = json_decode($result);
print_r($summoner->{''.$summonerName.''}->{'id'});
My issue here is {''.$summonerName.''}. I've posted the error below, and it appears to be a $ sign infront of the name... However when I use:
print_r($summoner->{'fksakes'}->{'id'});
It works; I've echo'd the $summonerName variable to see if it echo's "FkSakes", and not "$FkSakes" And it echo'd just FkSakes. I'm not to sure what's happening here...
[18-May-2015 10:51:02 UTC] PHP Notice: Undefined property: stdClass::$FkSakes in /testingground/test.php on line 22
An explanation to what's going on here would be just as good as a fix.
EDIT: Print_r($summoner);
stdClass Object ( [fksakes] => stdClass Object ( [id] => 801808 [name] => FkSakes [profileIconId] => 3 [summonerLevel] => 10 [revisionDate] => 1429436142000 ) )
Note that the notice Undefined property: stdClass::$FkSakes is the standard way to describe a missing property, so this is not due to an erroneous $:
error_reporting(-1);
$s = new stdClass;
var_dump($s->FkSakes); // Undefined property: stdClass::$FkSakes
Your problem here is that the property name is fksakes, not FkSakes (property names are case sensitive). You can therefore do the following:
$summonerName = strtolower($summoner[2]);
print_r($summoner->$summonerName->id); // 801808
Related
I'm trying to extract some variables from my REQUEST_URI:
liquidfinger.com/key1-value1/key2-value2/key3-value3
I want to transform these values into a php associative array. My code is as follows:
$pState = [];
$stateString = substr($_SERVER['REQUEST_URI'],1);//remove leading slash
if($stateString){
$statePairs = explode("/",$stateString);
foreach($statePairs as $statePair){
$statePairArray = explode("-",$statePair);
$pState[$statePairArray[0]] = $statePairArray[1];
}
}
The $pState array is being created correctly and I can echo all the keys and values. However, I am getting an error_log:
Undefined offset: 1
I am even getting an error_log when there are no key-value pairs, so the IF statement shouldn't be executed, but possibly that is a characteristic of the error_log?
Okay, just to recap, the code was working but I was getting error messages. Further tests yielded the following:
url: www.liquidfinger.com
print_r($pState): Array ( )
[11-Mar-2016 10:01:02 UTC] PHP Notice: Undefined offset: 1 in /home/adamglynsmith/public_html/index.php on line 20
url: http://www.liquidfinger.com/user-2/tab-browseAll/marker-101
print_r($pState): Array ( [user] => 2 [tab] => browseAll [marker] => 101 )
print_r($statePairArray): Array ( [0] => user [1] => 2 ) Array ( [0] => tab [1] => browseAll ) Array ( [0] => marker [1] => 101 )
[11-Mar-2016 10:14:41 UTC] PHP Notice: Undefined offset: 1 in /home/adamglynsmith/public_html/index.php on line 20
[11-Mar-2016 10:14:43 UTC] PHP Notice: Undefined offset: 1 in /home/adamglynsmith/public_html/index.php on line 20
Since I have spent quite enough time on it and since I ultimately wanted to end up with a JavaScript array, I solved - or avoided - the problem by using the php to construct a string for the JavaScript like so:
$stateString = str_replace("/","', ",$stateString);//get rid of slashes
$stateString = str_replace("-",":'",$stateString);//get rid of dashes
$stateString .= "'";//add final single quote
<script>
jState = {<?php echo $stateString; ?>};
</script>
Thanks.
PHP does not guard your code implicitly, so you have to do some extra work to make sure you're actually able to do the correct thing:
$pState = [];
$stateString = substr($_SERVER['REQUEST_URI'],1);//remove leading slash
if($stateString){
$statePairs = explode("/",$stateString);
if (count($statePairs)) >= 1 { // Technically unnecessary unless you want to log the fact you didn't find anything.
foreach($statePairs as $statePair){
$statePairArray = explode("-",$statePair);
if (count($statePairArray) == 2) { // Found two and only two elements
$pState[$statePairArray[0]] = $statePairArray[1];
} else {
//It is very helpful in log statements to include the values of things that produced unexpected results
Log.warn("Invalid key-pair found for statePairArray=" + $statePairArray);
}
}
} else {
LOG.warn("No state pairs found for stateString=" + $stateString);//Or some other appropriate log or exception
}
}
explode may return an empty array if there is nothing to explode on. Therefore you need to check and take an appropriate action if it isn't there.
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.
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'];
}
I am using the following code to get the number of likes on a page.
<?php
$site="http://graph.facebook.com/?ids=http%3a%2f%2fXXXXXXXX/svce.php";
$graph= file_get_contents($site);
$json_string=$graph;
$array = json_decode($json_string, true);
//echo "<pre>";
//print_r($array);
$var = $array['shares'];
echo $var;
?>
But whenever i try to echo out the following code. I always get an unidentified index Notice which is as following: Notice: Undefined index: shares in C:\xampp\htdocs\graphapi.php on line 19
Where am i going wrong?
Here's the print_r output:
Array
(
[http://xxxxxxxxx/svce.php] => Array
(
[id] => http://xxxxxxxxx/svce.php
[shares] => 7
[comments] => 3
)
)
According your print out looks like there is an array more in $array. Try this;
echo $array['http://xxxxxxxxx/svce.php']['shares'];
You have to use the site-name as an key before.
Structure:
- http://example.com
- id
- shares
This means in PHP:
$array["http://example.com/path/to/site"]["shares"];
Original SQL query is this;
SELECT id,post_title,post_date FROM wp_posts where id='1'
When I retrieve the record, I am finding it but when it comes to returning the results, I am puzzled. Here is the where I got stuck.
while ($row = mysql_fetch_assoc($RS)) :
print_r ($row);
list($id,$post_title,$post_date) = $row;
endwhile;
print_r ($row) outputs this;
Array ( [ID] => 1 [post_title] => Hello world! [post_date] => 2012-03-27 03:28:27 )
And when I run the list function in there ( for debug purposes obviously ), I get this;
Notice: Undefined offset: 2 in F:\inetpub\wwwroot\whatever\sql.php on line 147
Notice: Undefined offset: 1 in F:\inetpub\wwwroot\whatever\sql.php on line 147
Notice: Undefined offset: 0 in F:\inetpub\wwwroot\whatever\sql.php on line 147
What's causing this?
Replace:
mysql_fetch_assoc($RS)
with:
mysql_fetch_array($RS, MYSQL_NUM)
then it should work, because the list function trys to access the array using numeric keys.
I guess the answer lies somewhere within this;
list() only works on numerical arrays and assumes the numerical indices start at 0.
:(
You might be able to use extract() here instead, as well; (documentation here.)
You used mysql_fetch_assoc, so the resulting array per row has data under a key by column name, whereas "list" tries to match variables to values using numerical array indexes. You can use mysql_fetch_array instead.
$categ = val1 | val2
list($one,$two,$three)=#split('[|]',$categ);
If you try to list the value which is not available it will return the error Undefined Offset.
Here the error will be Undefined Offset 2.
Because while spliting $categ, it will have only two values, if you try to access third value then it will return error.