How to get a value from an array property?

Asked

Viewed 55 times

1

A VÁRIAVEL ARMAZENZA:

$parcelas = DB::select("SELECT parcela_number FROM parcelas WHERE 3000 BETWEEN valor_min AND valor_max");

VAR_DUMP:

   array(1) {
  [0]=>
  object(stdClass)#144 (1) {
    ["parcela_number"]=>
    int(3)
  }
}

GOAL:

$parcelas->parcela_number // RESULT 3
  • put, please, the var_dump($installments); then I can help you

  • Okay, I’ve posted the var_dump

  • ok try this: $parcelas[0]->parcela_number;

  • It worked, only I did not understand why, in another similar case works so $parcels[0]->value.

2 answers

2


André, come on, come on.

The var_dump() tool is very interesting because you understand the type of return you have. On your return we had the following:

array(1) {
  [0]=>
  object(stdClass)#144 (1) {
    ["parcela_number"]=>
    int(3)
  }
}

you note that the $parcela is a array. And then we have a objeto. The way to access data from array and of a objeto are different, so was not getting before. And for being a array we cannot access the data via -> and yes by position (index).

I make a foreach() in its variable $parcelas you will be able to retrieve the data via $parcela->

I can’t create a code for you, because I need more code from you to give you a practical example, but I believe you can easily.

To solve your problem do: $parcelas[0]->parcela_number;

1

According to Laravel’s documentation( https://laravel.com/docs/5.5/database#running-queries ), o Facade DB together with the select method. Ex:

$resultados = DB::select('select * from ...')

It will ALWAYS return an array and if there is a result, it will be an object within this array.

Thus, the access should be from an array.

$resultados[0]; // para acessar o primeiro resultado

or:

foreach($resultados as $resultado) {
    echo $resultado->key;
}

to access all results.

Namely: Interesting debug dd() and dump() methods available in Laravel.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.