MySQL - How extract value from stdClass when addressing by index or conversion to array fails

Cheshire Katzzze :

Currently making a study project, implementing a library in Laravel. I have written a procedure to calculate the amount of time a certain book was taken yearly:

$queryString = "SELECT ReadBookTakenPeriodPerYear({$id});";
$result = DB::select($queryString);

As a result, I am getting:

array (
  0 => 
  array (
    0 => 
    stdClass::__set_state(array(
       'ReadBookTakenPeriodPerYear(33)' => 1.91781,
    )),
  ),
) 

How can I get that 1.91781? Why can't I access the array by index, or convert the sdt-class to array? Researched for a solution on inet, on SO, still can't cope with it.

James Clark Developer :
array (
  0 => 
  array (
    0 => 
    stdClass::__set_state(array(
       'ReadBookTakenPeriodPerYear(33)' => 1.91781,
    )),
  ),
) 

You have a few layers of unneeded nesting in this return data. You have a php standard object which is the first and only element in an array. That array is the first and only element in a parent array. As it stands, you should be able to get the value like this:

$result[0][0]->ReadBookTakenPeriodPerYear(33);

You can simplify the returned data to make this slightly more straightforward by adding a ->first().

$result = DB::select($queryString)->first();

Adding ->first() here should eliminate one level of array. You are telling query builder to give you the first matching result rather than a collection of all of them. Now you should be able to do:

$result[0]->ReadBookTakenPeriodPerYear(33);

Combine this with use of the laravel helper Arr::get() to avoid an exception if no data is found in the database. https://laravel.com/docs/master/helpers#method-array-get

  Arr::get($result, 0)->ReadBookTakenPeriodPerYear(33);

And,finally, the Laravel helper method optional() to make sure $results[0] returned an object before looking for the attribute on it to avoid an exception at that level. https://laravel.com/docs/master/helpers#method-optional

  optional(Arr::get($result, 0))->ReadBookTakenPeriodPerYear(33);

That should get you the data, and also be able to handle cases where data wasn't found in the database without crashing.

I hope it helps!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169426&siteId=1