Reputation: 2006
If I perform the following query:
$lookupConnection = DB::connection(PZ_CONNECTION)->table($this->createLookupTable);
$lookupConnection->addSelect($lookupField);
$lookupConnection->where($searchField['data_lookup'], '=', $searchArray[$searchField['js_name']]);
$goodData = $lookupConnection->get();
dd($goodData);
This will work, and display an array containing an object.
Array(1) {
[0] =>
object(stdClass)#225 (2) {
["foo"] => string(3) "bar"
}
}
My problem is this, how do I access elements of the object without knowing what the element is?
I mean, the field is stored in $lookupField, however, I cannot run:
echo $goodData[0]->$lookupField
And if I try
echo $goodData[0][$lookupField]
I also get an error.
But if I try
echo $goodData[0]->foo
Then it works. But thats no good, as I don't know until runtime what the contents of $lookupField will be. I need to either output the query as an array, or access the object data via a variable, but I don't know how.
Upvotes: 0
Views: 145
Reputation: 2006
Ah, the problem was that I wasn't actually using
$lookupField
I was using
$anObject->$lookupfield[$n]
So the actual line would be
$goodData[0]->$anObject->lookupField[$n]
If instead I added
$lField = $anObject->lookupField[$n]
echo $goodData[0]->$lField
then that would work.
Upvotes: 0
Reputation: 179994
Works fine in my Laravel project:
$ php artisan tinker
[1] > $field = 'title';
// 'title'
[2] > $p = Promotion::all();
// object(Illuminate\Database\Eloquent\Collection)(
//
// )
[3] > $p[0]->$field;
// 'Test Promotion'
Or with the query builder:
$ php artisan tinker
[1] > $field = 'title';
// 'title'
[2] > $q = DB::table('promotions');
// object(Illuminate\Database\Query\Builder)(
// ...
// )
[3] > $q->addSelect('title');
// object(Illuminate\Database\Query\Builder)(
// ...
// )
[4] > $p = $q->get();
// array(
// 0 => object(stdClass)(
// 'title' => 'Test Promotion'
// )
// )
[5] > $p[0]->$field;
// 'Test Promotion'
Upvotes: 1