How to create an array dynamically in PHP?

1

I need to create an array in the format:

//$arr = ['id' => 1, 'razao_social' => 'Teste'] // saida esperada
// iteração
foreach($prestadores as $prestador){
    // logica separando apenas alguns prestadores
    if ($cont($outro_sql) > 1) {
        $dados = array_add($dados,'id',$prestador->id);
        $dados = array_add($dados,'razao_social',$prestador->razao_social);
    }
}

So far so good, but the result of array dd($dados) outputs the array, but only with the last record.

I need the array to be mounted with all the records.

    
asked by anonymous 14.11.2016 / 22:40

1 answer

2

I suggest learning the basics of language before doing anything more complex.

Here you test a condition within a loop , it will not change, so either it will add everything, or it will not add anything:

if ($cont($outro_sql) > 1) {

If the condition is fixed, it is the case of testing out loop instead of repeating the whole test. If it was to rely on the current record, you need to correct the logic. It may be that you are calling a variable function as well, there would even make some sense, but in view of the rest of the code I suggest analyzing if that is what you want. I find construction strange.

In this section you are continuously overwriting the variable $dados :

    $dados = array_add($dados,'id',$prestador->id);
    $dados = array_add($dados,'razao_social',$prestador->razao_social);

Another thing is to want to store result of array_add (would be the case of array_push ), which returns the last value. When you use array_push you normally do not have to do any assignments.

Unless, of course, you have written a array_add function that returns the array added to it, but then it would really be a problem for you to determine how to% % and id correct.

Probably (this is what you could understand as the example in the code comment) would be the case to do something like this:

    $dados[] = array(
      'id' => $prestador->id,
      'razao_social' = $prestador->razao_social
    );

Or this:

    array_push( $dados,
       array( 'id' => $prestador->id, 'razao_social' => $prestador->razao_social )
    );

Or this, to illustrate in another way:

    $dados = array();

    $par = array();
    $par['id'] = $prestador->id;
    $par['razao_social'] = $prestador->razao_social;

    array_push( $dados, $par );

When you assign a value using empty index ( razao_social ), PHP adds an element to the end of the array

I would suggest a more in-depth reading of the manual to understand the basic elements of language, and to do little exercises to master each concept:

  

link

    
14.11.2016 / 22:55