Ended up with an Object, how do I work with this?

2019-08-10 06:06发布

问题:

After solving part of my problem over here, I realized that I could get the data into the view, but then I had another problem.

(controller)

$this->load->model('testing/test_v_to_m_model');
$data['mydata'] = $this->test_v_to_m_model->display_character_info();
$this->load->view('testing/test_v_to_m_view', $data);

(model)

$query = $this->doctrine->em->createQuery("select u from ORM\Dynasties2\Characters u");
return $query->getResult();

(view)

foreach ($mydata as $key => $row) {
   print_r($row);
}

This returns output like so:

ORM\Dynasties2\Characters Object ( [id:ORM\Dynasties2\Characters:private] => 76 [name:ORM\Dynasties2\Characters:private] => Gwayn [whichFamily:ORM\Dynasties2\Characters:private] => 12 [bornDate:ORM\Dynasties2\Characters:private] => -467 [deathDate:ORM\Dynasties2\Characters:private] => -6 [marriedTo:ORM\Dynasties2\Characters:private] => 77 [marriedDate:ORM\Dynasties2\Characters:private] => -304 [marriageCode:ORM\Dynasties2\Characters:private] => [religion:ORM\Dynasties2\Characters:private] => 0 [isFemale:ORM\Dynasties2\Characters:private] => 0 [betrothedTo:ORM\Dynasties2\Characters:private] => [fathersId:ORM\Dynasties2\Characters:private] => 0 [successionOrder:ORM\Dynasties2\Characters:private] => 0 [isPregnant:ORM\Dynasties2\Characters:private] => [pregnantTurnsLeft:ORM\Dynasties2\Characters:private] => [marriedOutOfFamily:ORM\Dynasties2\Characters:private] => [bornMatrilineal:ORM\Dynasties2\Characters:private] => )

And so... I just don't know how to do anything with this- I tried a nested foreach to echo data and couldn't get it to work. I expect that its because this is an Object, not an Array, is that correct?

  1. How exactly can I access/manipulate these fields?

  2. Is there different code that I can use in my Doctrine2/CodeIgniter2 model that will give the data easier field names - like the equivalent to sql AS?

回答1:

You should be able to access the object with pointers, like so:

foreach ($mydata as $key => $row) {
   echo($row->id);
   echo($row->name);
}

stdClass is php's generic empty class. Here is a nice tutorial on using this: http://krisjordan.com/dynamic-properties-in-php-with-stdclass

Edit:

Try using an accessor:

echo($row->getId());