Change array keys returned by mysqli_result

Asked

Viewed 710 times

3

I need to change the keys of a result obtained by mysqli_result->fetch_assoc()

If I do this research :

"SELECT exemplo.nome, exemplo.apelido, exemplo.idade FROM exemplo WHERE exemplo.id=1"

get this result

$result["nome"]= "António";
$result["apelido"] = "Silva";
$result["idade"] = "30";

and would like to receive or transform into :

$result["exemplo.nome"]= "António";
$result["exemplo.apelido"] = "Silva";
$result["exemplo.idade"] = "30";

I can’t use aliases in the search phrases

"SELECT exemplo.nome as exemplo.nome , exemplo.apelido as exemplo.apelido, exemplo.idade  as exemplo.idade FROM exemplo WHERE exemplo.id=1";

Any suggestions?

  • 2

    But why do you want to do it?

  • You can go by "example name" if it helps...

  • Pq you cannot use alias this column is called after?

  • I am so sorry, but this is the problem that I have. It is no use to question why it has to be like this. I can only touch the keys of the result.

  • Then you need to reindexe the entire array with that prefix exemplo?

  • Could be an @rray solution

  • 2

    @Manuelgerardopereira can create a view in the bank?

Show 2 more comments

1 answer

1

Based on this response from Soen you can rename the array keys with the prefix using array_map, the most recommended would be to use an alias as is not possible, the other option would be to create a view as told by gmsantos.

$arr_entrada = array(
            array('nome'=>'joão', 'apelido' => 'j ', 'idade' => '20'),
            array('nome'=>'mario','apelido' => 'm', 'idade' => '28'));

echo'<pre>';
print_r($arr_entrada);


$arr_saida = array_map(function($input) {
    return array(
        'exemplo.nome' => $input['nome'],
        'exemplo.apelido' => $input['apelido'],
        'exemplo.idade' => $input['idade']
    );
}, $arr_entrada);

echo'<pre>';
print_r($arr_saida);

Example

Browser other questions tagged

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