iterating through a stdClass object in PHP

后端 未结 5 955
我寻月下人不归
我寻月下人不归 2020-12-03 14:04

I have an object like this:

stdClass Object
(
    [_count] => 10
    [_start] => 0
    [_total] => 37
    [values] => Array
        (
                    


        
相关标签:
5条回答
  • 2020-12-03 14:39
    function objectToArray( $data ) 
    {
        if ( is_object( $data ) ) 
            $d = get_object_vars( $data );
    }
    

    Convert the Object to array first like:

    $results = objectToArray( $results );
    

    and use

    foreach( $results as result ){... ...}
    
    0 讨论(0)
  • 2020-12-03 14:44
    foreach($res->values as $value) {
        print_r($value);
    }
    
    0 讨论(0)
  • 2020-12-03 14:45

    Since this is the top result in Google if you search for iterate over stdclass it may be helpful to answer the question in the title:

    You can iterate overa stdclass simply by using foreach:

    $user = new \stdClass();
    $user->flag = 'red';
    
    foreach ($user as $key => $value) {
       // $key is `flag`
       // $value is `red`
    }
    
    0 讨论(0)
  • 2020-12-03 14:50
    echo "<table>"
    
    foreach ($object->values as $arr) {
        foreach ($arr as $obj) {
            $id   = $obj->group->id;
            $name = $obj->group->name;
    
            $html  = "<tr>";
            $html .=    "<td>Name : $name</td>";
            $html .=    "<td>Id   : $id</td>";
            $html .= "</tr>";
        }
    }
    
    echo "</table>";
    
    0 讨论(0)
  • 2020-12-03 14:56

    I know it's an old post , but for sake of others: when working with stdClass you should use Reflections:

      $obj = new ReflectionObject($object);
    
      $propeties = $obj->getProperties();
    
          foreach($properties as $property) {
            $name = $property->getName();  <-- this is the reflection class
            $value = $object->$name;       <--- $object is your original $object
    
                here you need to handle the result (store in array etc)
    
    
    
            }
    
    0 讨论(0)
提交回复
热议问题