Laravel: object unable to access its properties - php

Let's say I have a function which returns an object with one of it's parameters set to some certain value:
public function search($jobsdone, $date)
{
foreach ($jobsdone as $jd) {
if ($jd->date_worked == $date) return $jd;
}
}
Printing search($jobsdone, $key) yields such results:
object(JobDone)#378 (19) {
...
["attributes":protected]=>
array(9) {
["id"]=>
int(3593)
["user_id"]=>
int(13)
["object_id"]=>
int(99)
["job_id"]=>
int(130)
["date_worked"]=>
string(10) "2013-10-01"
["min_from"]=>
int(780)
["min_to"]=>
int(1080)
}
...
}
However, if I want to print out search($jobsdone, $key)->id, all I get is an error message of:
Trying to get property of non-object
What could I be missing here?

Your search function doesn't always return an object. Therefore, you get error Trying to get property of non-object whenever your search couldn't find a $jobdone object.

Related

PHP Check if Key Exists in Multidimensional Array and Object Combination then Get Value

I am querying an API and the response I get is a Multidimensional Object object(stdClass) that also contains arrays. I need to be able to check if the response is an error condition or was successful. If the response is successful I need to return TRUE. If the response was an error, I need to return the error message contained in the response. The response formats for success and error are completely different. The response for an error looks like this:
object(stdClass)#837 (3) {
["errors"]=> array(1) {
[0]=> object(stdClass)#838 (2) {
["code"]=>int(324)
["message"]=>string(80) "Duration too long, maximum:30000, actual:37081 (MediaId: snf:840912013693931526)"
}
}
["httpstatus"]=>int(400)
["rate"]=>NULL
}
The response for success looks like this:
object(stdClass)#837 (27) {
["created_at"]=> string(30) "Sun Mar 12 13:41:43 +0000 2017"
["id"]=> int(840920745073102850)
["id_str"]=> string(18) "940920795073102850"
["text"]=> string(32) "The Details Posted Here"
["truncated"]=> bool(false)
["entities"]=> object(stdClass)#838 (5) {
["hashtags"]=>
........ Way More is in the Response but it does not matter...
I have tried changing the response to an array then using isset to establish if it was an error, and if so then get the values of the error details like so:
$RESPONSEARRAY = (array) $RESPONSE;
(isset($RESPONSEARRAY["errors"])) {
$ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]['code'];
$ERRORMSG_MESSAGE = $RESPONSEARRAY['errors'][0]['message'];
$ITWASANERROR = $ERRORMSG_CODE.": ".$ERRORMSG_MESSAGE;
return $ITWASANERROR;
} else {
return true;
}
But doing the above give me the following error:
Fatal error: Cannot use object of type stdClass as array
Can anyone suggest a way of doing what I am trying to do with the least overhead on the server. Maybe without needing to convert the stdClass object to an array, or if that has to be done, then that's fine, but I just need it to work. Any help someone can offer would be super appreciated.
Below is the correct way to access the object inside the array.
$RESPONSEARRAY = (array) $RESPONSE;
if(isset($RESPONSEARRAY["errors"])) {
$ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]->code;
$ERRORMSG_MESSAGE = $RESPONSEARRAY['errors'][0]->message;
$ITWASANERROR = $ERRORMSG_CODE.": ".$ERRORMSG_MESSAGE;
return $ITWASANERROR;
} else {
return true;
}
$RESPONSEARRAY = (array) $RESPONSE;
You can get result:
["errors"]=>
array(1) {
[0]=>
object(stdClass)#1 (2) {
["code"]=>
int(324)
["message"]=>
string(80) "Duration too long, maximum:30000, actual:37081 (MediaId: snf:8
40912013693931526)"
}
}
["httpstatus"]=>
int(400)
So $ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]['code']; should be $ERRORMSG_CODE= $RESPONSEARRAY['errors'][0]->code.
And so on

How to access an element in an array in PHP

Hi I am trying to access a property of an object from an array but seems to not getting it correctly. I have an array of objects that is posted in PHP.
$classrooms = $_POST->client->classrooms
when I do a var_dump($classrooms) I get the structure like below:
array(1) {
[0]=>
array(2) {
[0]=>
object(stdClass)#5 (4) {
["classroomid"]=>
int(2)
["classroom"]=>
string(7) "Grade 1"
}
[1]=>
object(stdClass)#6 (4) {
["classroomid"]=>
int(4)
["classroom"]=>
string(9) "Grade 2"
}
}
}
I am trying to access "classroom" property using following code in PHP but it does not output anything.
foreach($classroom as $item)
{
echo $item['classroom'];
}
But if try like this (by hardcoding index) it gives me correct name of classrooms but I cannot pass the index as I do not know how many will be in the array.
foreach($classroom as $item)
{
echo $item[0]['classroom'];
}
Thank you for reading this.
Try like this,
$lists = [];
foreach($classroom as $item)
{
foreach($item as $k => $v){
$lists[] = $v->classroom; // or $v->classroom;
}
}
print_r($lists);
For stdClass object you have to use "->" to get the key value.
foreach($classroom as $subarray) {
foreach($subarray as $item) {
echo $item->classroom;
}
}
If you use $item['classroom'] it will throw an error:
PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array.

Can't access value of protected static variable php 7.0.13

I'm trying to implement a DataTable class in php which will be basically a table to contain data just like an sql table and will be made of array()
The class is defined as followed:
class DataTable{
protected static $tabela; // table
//columns and strips, each column point to a strip
public function __construct($colunas, $faixas) {
$this->tabela = array();
$this->constroiDt($colunas, $faixas); //builds the table
}
public function getRows($where){
// todo
}
public static function getTabela(){
return $this->tabela;
}
private function constroiDt($colunas, $faixas){
if(count($colunas)!= count($faixas)){
$this->tabela = null;
return;
}
$i=0;
foreach($colunas as $cl){
$this->tabela = array_merge($this->tabela, array($cl => $faixas[$i]));
$i += $i + 1;
}
// the result will be an array like ('col1' => ('val1','val2'), 'col2' => ('val1','val2'))
// if I want to access a value, just type array['col1'][0] for example
}
}
Outside of the class function, when I create an example DT and try to access it, it seems that will work:
$columns = array("name", "age");
$strips = array(array("someone","another person"),array("20","30"));
$dt1 = new DataTable($columns, $strips);
var_dump($dt1); // will print:
// object(DataTable)#1 (1) { ["tabela"]=> array(2) { ["nome"]=> array(2) { [0]=> string(6) "fulano" [1]=> string(7) "ciclano" } ["idade"]=> array(2) { [0]=> string(2) "20" [1]=> string(2) "30" } } }
But then I add echo "--- " . $dt1::getTabela()['nome'][0];
It doesn't even print the ---. var_dump($dt1::getTabela()) and var_dump($dt1->getTabela()) also is blank. What is being missed here? Tried also this but didn't work.
You shouldn't use $this in a static function / for static properties as there is not necessarily an object context to use.
Instead, you should use self::$tabela everywhere instead.
Or change your variable (and the related methods...) to a "normal" protected property:
protected $tabela;
You are mixing static variables with non static accesors
i just put your code and i got a lot of errors/notices
NOTICE Accessing static property DataTable::$tabela as non static on line number 10
NOTICE Accessing static property DataTable::$tabela as non static on line number 31
NOTICE Accessing static property DataTable::$tabela as non static on line number 31
NOTICE Accessing static property DataTable::$tabela as non static on line number 31
NOTICE Accessing static property DataTable::$tabela as non static on line number 31
object(DataTable)#1 (1) { ["tabela"]=> array(2) { ["name"]=> array(2) { [0]=> string(7) "someone" [1]=> string(14) "another person" } ["age"]=> array(2) { [0]=> string(2) "20" [1]=> string(2) "30" } } }
FATAL ERROR Uncaught Error: Using $this when not in object context in /home/phptest/public_html/code.php70(5) : eval()'d code:20 Stack trace: #0 /home/phptest/public_html/code.php70(5) : eval()'d code(44): DataTable::getTabela() #1 /home/phptest/public_html/code.php70(5): eval() #2 {main} thrown on line number 20

Use php to display specific "key-value" pair from the data retrieved from the mongodb

This is the php code.
<?php
// connect to mongodb
$m = new MongoClient();
// select a database
$db = $m->Example;
$collection="User";
$Query = array("Username"=>$username);
$j = $db->$collection->find($Query);
foreach ($j as $k) {
echo"<pre>";var_dump($k); echo"</pre>";
}
foreach($j as $k => $v) {
echo $k.'='.$j[$k].'<br>';
}
?>
In this, the data is retrieved in $j variable an when var_dump($k) is used the output is as follows:
array(8) {
["_id"]=>
object(MongoId)#6 (1) {
["$id"]=>
string(24) "56d1cb49097ed3241d000029"
}
["Fname"]=>
string(4) "Ritu"
["Lname"]=>
string(3) "Rad"
["Username"]=>
string(4) "riri"
["Password"]=>
string(4) "riri"
["Email"]=>
string(23) "ritikatra#gmail.com"
}
But if you try to display individual key value pair as in the next foreach loop you get the following error:
Fatal error: Cannot use object of type MongoCursor as array
How to display only a particular key and it's value?
eg: Email ritikatra#gmail.com
Result of \MongoCollection::find() (your $j) variable is an instance of \MongoCursor class which implements \Iterator - it allows you to loop over it but it doesn't have keys (i.e. doesn't implement \ArrayAccess). If you want to use your results as an array you should call
$array = iterator_to_array($j);
Now you can use $array as it'd be plain array:
echo $array[0]['Email']

php array of objects can't get object property (Object of class stdClass could not be converted to string)

been searching for a solution all day long...
my variable name is $categoryFetchedAsObj
var_dump results :
array(104) {
[0]=>
object(stdClass)#411 (1) {
["categoryHive"]=>
string(4) "asfa"
}
[1]=>
object(stdClass)#412 (1) {
["categoryHive"]=>
string(13) "ENERGY DRINKS"
}
[2]=>
object(stdClass)#413 (1) {
["categoryHive"]=>
string(7) "KETCHUP"
}
[3]=>
object(stdClass)#414 (1) {
["categoryHive"]=>
string(6) "STICKS"
}
and so on
i call a function...
createSelectBlock("category",$categoryFetchedAsObj,"onchange=\"this.form.submit()\"",null,'categoryHive');
here is the instance of the function
createSelectBlock($name,$fetchedNamesAsArrayOfObj,$selectEvent,$objPropertyNameForOptionsValue,$objPropertyNameForOptionsName)
and here is where the error raises
foreach ($fetchedNamesAsArrayOfObj as $rowArrayObj) {
if(isset($objPropertyNameForOptionsValue) && isset($objPropertyNameForOptionsName)){
$selectBlock.="<option value=\"$rowArrayObj->$objPropertyNameForOptionsValue\">$rowArrayObj->$objPropertyNameForOptionsName</option>";
}
if(!isset($objPropertyNameForOptionsValue) && isset($objPropertyNameForOptionsName)){
$selectBlock.="<option value=\"$rowArrayObj->$objPropertyNameForOptionsName \">$rowArrayObj->$objPropertyNameForOptionsName</option>";
}
}
(Object of class stdClass could not be converted to string)
if i replace the
$rowArrayObj->$objPropertyNameForOptionsName
with
$rowArrayObj->categoryHive
everything works but the args of the function are not the same all the time .. obviously
i search this site found some suggestions.. but nothing worked
here is what i tryied
$objPropertyNameForOptionsName='$objPropertyNameForOptionsName';
$rowArrayObj->{'$objPropertyNameForOptionsName'};
any ideas?
after testing and over testing .. finlay i got it working...
this was the correct answer for my situation
if(isset($objPropertyNameForOptionsValue) && isset($objPropertyNameForOptionsName)){
$selectBlock.="<option value=".$rowArrayObj->$objPropertyNameForOptionsValue.">".$rowArrayObj->$objPropertyNameForOptionsName."</option>";
}
if(!isset($objPropertyNameForOptionsValue) && isset($objPropertyNameForOptionsName)){
$selectBlock.="<option value=".$rowArrayObj->$objPropertyNameForOptionsName.">".$rowArrayObj->$objPropertyNameForOptionsName."</option>";
}
hope it helped someone

Categories