How to create an array dynamically in PHP?

Asked

Viewed 1,235 times

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 the array dd($dados) has as output the array, but only with the last record.

I need the array to be mounted with all records.

See, I know $provider is already an array, but I need to build a BD access logic by accessing other tables, where only a few records will compose this new array.

1 answer

2


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

Here you test a condition within a loop, and she won’t change, so either she’ll add everything, or she won’t add anything:

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

If the condition is fixed, it is the case to test outside the loop instead of repeating the test altogether. If it was to depend on the current record, you need to correct the logic. It may be that you are calling a variable function as well, then it would make some sense, but in view of the rest of the code I suggest analyzing if this is what you want. It seems strange to me the construction.

Already in this excerpt 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 wanting to store result of array_add (it would be the case of array_push), which returns the last value. When using array_push usually do not need to do assignments.

Unless, of course, you’ve written a function array_add to return the array added on itself, but then really it would be suffered you determine how to make the "pair" of id and razao_social correct.

Probably (this is what we could understand according to 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 even this, to illustrate otherwise:

    $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 ([]), PHP adds an element at the end of array

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

http://php.net/manual/en/index.php

  • Bacco thanks for the help and advice. For the record and I read the manual and was not able to assemble the logic, so I used this tool. Wouldn’t if I had. Thanks, it worked.

  • @Marcelogomes, especially on the arrays part, PHP has several specificities. It’s kind of boring to read documentation, but if you’re reading and doing small, piecemeal tests, it helps to absorb the concepts. A very common problem is trying to understand the function using more complex code, confuses. Whenever you need to master a new concept, test it separately. Create a script for testing, and try variations on it to observe the effects, the manual serves as a support, but trying it is always interesting. In your case, note that it is not a simple array, but an array of other arrays.

  • Note that this I am recommending, to test things separately, I usually do today, even knowing PHP at least some 15 years ago. It is never enough to solve the problems separately and join in the final application. You end up isolating the problems a lot, and making a code naturally more streamlined and organized by dividing the problem into parts.

  • Anyway, if you have any questions about this same subject, you can leave a comment here and I’ll supplement the answer when you can, and if you have any further questions, please open new questions. That’s what we’re here for. The recommendations are for you to gain autonomy, but whenever you try something and don’t succeed, don’t be afraid to ask.

  • Bacco, thanks for sharing your experience. Thanks Even. Hugs.

Browser other questions tagged

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