I have a wordpress function that calls an API via Zebra_cURL and then uses json_decode to render the data appropriately. Yet there is erratic behavior and the following two errors are occurring: Trying to get property of non-object in [template file] on line 42 and through lines 50.
The lines in question are below:
//Course display callback function
function display_courses($result) {
$result->body = json_decode(html_entity_decode($result->body));
$title = $result->body[0]->{'Title'};
$term = $result->body[0]->{'Term'};
$meetings = $result->body[0]->{'Meetings'};
$status = $result->body[0]->{'Status'};
$course_number = $result->body[0]->{'OfferingName'};
$clean_course_number = preg_replace('/[^A-Za-z0-9\-]/', '', $course_number);
$credits = $result->body[0]->{'Credits'};
$instructor = $result->body[0]->{'InstructorsFullName'};
$description = $result->body[0]->{'SectionDetails'}[0]->{'Description'};
}
And then later I get an error Invalid argument supplied for foreach() in [template file] on line 64 which is:
//Call callback function
function parse_courses($result) {
$result->body = json_decode(html_entity_decode($result->body));
$course_data = array();
foreach($result->body as $course) {
[code]
}
[more code]
}
What exactly am I doing wrong here to cause these errors?
Here's a link to the full template file. Apologies for the vast code dump but I'm a bit in over my head with this.
You must always verify the output of functions/methods if the result if "as expected"
In your case, you did not check what json_decode() has returned
function parse_courses($result) {
$result = json_decode(html_entity_decode($result->body));
if ((!is_array ($result) && !is_object($result)) ||
(is_array($result) || count($result) == 0) ||
(json_last_error() != JSON_ERROR_NONE)) { // only for PHP >= 5.3.0
// log the error or warning here ...
// $input = $result;
// $output = print_r ($result, TRUE);
// Only for PHP >= 5.3.0
// json_last_error();
// json_last_error_msg();
return -1;
}
$result->body = $result;
$course_data = array();
foreach($result->body as $course) {
[code]
}
[more code]
}
Related
I got a whole heap of (foreach()) warnings on my server log. Could they be causing sql timeout on my db via a sql connection leak?
I'm not entirely sure how to resolve the problem but i read that i need to add this bit of code:
if (is_array($values) || is_object($values))
{
foreach ($values as $value)
{
...
}
}
...into my .php but dont really know where to add it or why? sorry noob here again.
Here's my code section for: PHP Warning:
Invalid argument supplied for foreach() in
/hermes/bosnacweb03/bosnacweb03aa/b1245/ipg.tinsflowershop/panga/classes/ImageType.php
on line 148
(Line 148 starts - foreach ($results as $result) {)
/**
* Finds image type definition by name and type
* #param string $name
* #param string $type
*/
public static function getByNameNType($name, $type = null, $order = 0)
{
static $is_passed = false;
if (!isset(self::$images_types_name_cache[$name.'_'.$type.'_'.$order]) && !$is_passed) {
$results = Db::getInstance()->ExecuteS('SELECT * FROM `'._DB_PREFIX_.'image_type`');
$types = array('products', 'categories', 'manufacturers', 'suppliers', 'scenes', 'stores');
$total = count($types);
foreach ($results as $result) {
foreach ($result as $value) {
for ($i = 0; $i < $total; ++$i) {
self::$images_types_name_cache[$result['name'].'_'.$types[$i].'_'.$value] = $result;
}
}
}
$is_passed = true;
}
I assume that all the warnings on my log are the same issue? eg:
PHP Warning: Invalid argument supplied for foreach() in
/hermes/bosnacweb03/bosnacweb03aa/b1245/ipg.tinsflowershop/panga/classes/Category.php
on line 594
when i try use in_array function in php for the second time for same array variable i got the following error saying:
in_array() expects parameter 2 to be array, string given in
when i wrap the function in condition is_array, it returns false, i already print the variable using print_r and its showing array structure, here's the code:
$chosenCour = array();
$chosenServ = array();
foreach ($preferences as $preference) {
if(!in_array($preference['courier'],$chosenCour)){
$chosenCour[] = $preference['courier'];
}
if(!in_array($preference['courier_service'],$chosenServ)){
$chosenServ[]= $preference['courier_service'];
}
}
foreach ($couriers as $courier) {
$courCond = false;
if(is_array($chosenCour)){
if(in_array($courier['courier_id'],$chosenCour)){
$courCond = true;
}
}
}
Check the additional condition for non empty array
foreach ($couriers as $courier) {
$courCond = false;
if(is_array($chosenCour) && count($chosenCour) > 0){
if(in_array($courier['courier_id'],$chosenCour)){
$courCond = true;
}
}
}
I'm not too sure what exactly it is I'm doing wrong, and I did check with other questions, and all I kind of inferred was that returning (something called "empty") only supports variables, although that didn't really change anything.
I am getting a very strange error in my code when I run it, and can't make head or tails of it.
Fatal error: Can't use function return value in write context in /home/shortcu1/public_html/projects/friendcodes/newUser.php on line 103
This is the main function that's being called. (in a file called newUser.php)
function isBumping($forumid, $username, $premium){
if($premium == 'true'){
$file = file_get_contents('plist.txt'); // This is the file I'm testing on
echo 'Running code as premium<br>';
} else {
$file = file_get_contents('list.txt');
}
$forumid = $forumid.':'.$username;
$posts = explode(' ', $file);
$posts ($info, $bump) = array_filter($posts, function($item) use ($forumid, $posts){
// This will check for matching forum ID
if(strpos($item, $forumid) !== true){
$pos = strpos($item, ':Day-');
$pos = $pos + 5;
$day = (int) substr($item, $pos, 1); // Converts the stored date to a numerical value. remember 1 = monday, 7 = sunday
$today = date('N');
$bump = false;
if(($day+3) % 7 > $today){
// Old enough to re-bump
return array ($item, $bump);
} else {
// Too recent to re-bump
$bump = true;
return array ($item, $bump);
}
}
});
print_r($posts[1]);
echo '<br>';
print_r($posts[2]);
}
It is being run through the file test.php:
include('newUser.php');
isBumping(1, 'Spitfire', 'true')
The file called plist.txt is as follows:
1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:90
1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:90
1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:90
1:Spitfire:Day-4:8JX-UKR8:8JX-UKR8:Spirit:90
Try changing
$posts ($info, $bump) =
to
$posts =
array_filter returns the array having all non empty element of the array.
You cann't use $post($a, $b) for this
try changing to to a variable
like simply $post.
I have a fatal error claiming that I have a string when I thought I had an array :
Fatal error: [] operator not supported for strings in /Applications/MAMP/htdocs/tankards_wordpress/wp-content/themes/tankardsleague/functions.php on line 566
and also the following warning :
Warning: in_array() expects parameter 2 to be array, string given in /Applications/MAMP/htdocs/tankards_wordpress/wp-content/themes/tankardsleague/functions.php on line 579
I am guessing that I have either a syntax problem somewhere? I thought I had initailized the variables but maybe I missed one? I would appreciate some more experienced eyes having a look.
function forum_subscribe_member_player()
{
global $user_ID;
$players= get_users();
foreach($players as $player)
{
$user_info = get_userdata($player->ID);
$playeremail = $user_info->user_email;
if(!empty($playeremail) && user_can( $player-> ID, 'contributor'))
{
$list = get_option('mf_forum_subscribers_1', array());
if( is_player_subscribed($player->ID)) //remove player if already exists (user clicked unsubscribe)
{
$key = array_search($playeremail, $list);
unset($list[$key]);
}
else
$list[] = $playeremail;
update_option('mf_forum_subscribers_1', $list);
}
}
}
function is_player_subscribed($user_ID)
{
if($user_ID)
{
$useremail = get_userdata($user_ID, 'user_email');
$list = get_option("mf_forum_subscribers_1", array());
if(!empty($list) && in_array($useremail, $list))
{
return true;
}
return false;
}
}
function call_forum_subscribe_member_player()
{
forum_subscribe_member_player();
}
line 566 is $list[] = $playeremail; line 579 is if(!empty($list) && in_array($useremail, $list))
well, you can type-cast the $list to an array to make sure it's always an array even if the initial value is null/empty/etc (basically any type except array):
$list = (array)get_option('mf_forum_subscribers_1', array());
So I have the following XML chain:
$xml->assessment->outcomes_processing->outcomes->decvar->attributes()->cutvalue
XML example
In Some XML-files $xml->assessment->outcomes_processing->outcomes->... does exist. But here only $xml->assessment exist.
<questestinterop>
<assessment ident="nedolat78356769204914" title="welkom woordenschat 4">
<qtimetadata>
<qtimetadatafield>
<fieldlabel>qmd_assessmenttype</fieldlabel>
<fieldentry>Assessment</fieldentry>
</qtimetadatafield>
</qtimetadata>
<section ident="nedolat78356769204915" title="Woordenschat">
<selection_ordering>
<selection/>
<order order_type="Sequential"/>
</selection_ordering>
<item ident="QTIEDIT:FIB:34932158" title="Oefening 1">
...
</item>
</section>
</assessment>
</questestinterop>
At the moment I am receiving the error: "Trying to get property of non-object". Which is logic because the node from outcomes doesn't exist.
So I tried a solution with isset() which obviously isn't working either.
isset($xml->assessment->outcomes_processing->outcomes->decvar->attributes()->cutvalue) ? ... : null
This gives me the same error. Because the node outcomes doesn't exist, so he throws me the error immediately. The solution could be for checking each node individually with isset(), of course with a function because otherwise I have a lot of checking to do...
This is my function, which is failed to work because the string '->' could not be processed as php code:
// xml: xml structure form SimpleXML
// chain: assessment->outcomes_processing->outcomes->decvar->attributes()->cutvalue
function checkIfXMLChainExists($xml, $chain) {
$xmlChain = '';
$i = 0;
$nodes = explode('->', $chain);
$numItems = count($nodes);
// experimenting with eval() to treat '->' as ->; failed to work
$a = '$xml->assessment->outcomes_processing';
$t = eval($a);
echo $t;
print_r($t);
foreach ($nodes as $node) {
$xmlChain .= '->' . $node;
if (isset($xml->$xmlChain)) { // Node exists
if ($i+1 == $numItems) {
return $xml->$xmlChain;
}
} else { // Node does not exists
return 'does not exist';
}
$i++;
}
Does anyone has some ideas because I don't have any inspiration at the moment :(
Thanks in advance
Returns the data referenced by the chain, or NULL if it doesn't exist.
function getDataIfExists () {
// We accept an unknown number of arguments
$args = func_get_args();
if (!count($args)) {
trigger_error('getDataIfExists() expects a minimum of 1 argument', E_USER_WARNING);
return NULL;
}
// The object we are working with
$baseObj = array_shift($args);
// Check it actually is an object
if (!is_object($baseObj)) {
trigger_error('getDataIfExists(): first argument must be an object', E_USER_WARNING);
return NULL;
}
// Loop subsequent arguments, check they are valid and get their value(s)
foreach ($args as $arg) {
$arg = (string) $arg;
if (substr($arg, -2) == '()') { // method
$arg = substr($arg, 0, -2);
if (!method_exists($baseObj, $arg)) return NULL;
$baseObj = $baseObj->$arg();
} else { // property
if (!isset($baseObj->$arg)) return NULL;
$baseObj = $baseObj->$arg;
}
}
// If we get here $baseObj will contain the item referenced by the supplied chain
return $baseObj;
}
// Call it like this:
$subObj = getDataIfExists($xml, 'assessment', 'outcomes_processing', 'outcomes', 'decvar', 'attributes()', 'cutvalue');