Show concrete data of array with objects [duplicate]

33
February 11, 2019, at 4:20 PM

This question already has an answer here:

  • Fatal error: Cannot use object of type User as array 1 answer
  • PHP Error: Cannot use object of type stdClass as array (array and object issues) [duplicate] 6 answers
  • How can I access an array/object? 4 answers

I want to show a specific data of an array, I have the following code and I am trying to print the printConcreteStudent function to print a specific student that I indicate passed through the variable $name.

When trying to find the student I get the following error:

Fatal error: Uncaught Error: Can not use object of type Student as array

The structure of the array is as follows:

array(1) {
  [0]=>
  object(Student)#1 (4) {
    ["name"]=>
    string(5) "Student1"
    ["lastname":"Student":private]=>
    string(7) "lastName1"
  }
}

And the function with which I am trying to print a specific data :

function printConcreteStudent($name) {
    foreach($this->students as $key=>$value){
        if($value["name"] == $name){
            echo $value->getName() . " ";
            echo $value->getLastName() . " ";
        }
    }
}
Answer 1

As you error state you can use object as array. In $this->students every object is of type object(Student) so you can access the name field by using "key" index. You need to change: if($value["name"] == $name){ (because cannot use $value["name"] as $value is object) to:

if($value->getName() == $name){
Answer 2

students is array of object so value is an object so $value->name; is how you will access the name attribute

   foreach($this->students as $key=>$value){
     if($name==$value->name){
      //print the attributes...  
     }
   }

It's better to lower case both of the values and then compare so that it may find the result even if capital letters are entered as input

READ ALSO
No styling when converting DOCX into PDF

No styling when converting DOCX into PDF

I am trying to convert a DOCX file to PDF with PHPWordWhen I execute the script it looks like that some style elements are not converted

37
Connection Failed: php_network_getaddresses: getaddrinfo failed: No such host is known

Connection Failed: php_network_getaddresses: getaddrinfo failed: No such host is known

Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: No such host is knownin C:\xampp\htdocs\Hostel-Management-System-master\includes\config

51
How to differentiate data to be read between two tables when username and password is passed

How to differentiate data to be read between two tables when username and password is passed

I am using volley in my mobile development login and instead of one table, I used two

41
Avoid inserting duplicate data in csv with PHP

Avoid inserting duplicate data in csv with PHP

I store data into a csv file by this:

37