Convert php array

Asked

Viewed 37 times

-2

How do I turn this array:

$rs = 
Array
(
    [0] => Array
        (
            [DESCRICAO] => cadastrar
        )

    [1] => Array
        (
            [DESCRICAO] => editar
        )

    [2] => Array
        (
            [DESCRICAO] => deletar
        )

)

in

array(cadastrar,editar,deletar)

I’m trying to do:

$permissao = 'editar';

if(in_array($permissao ,$rs)){
  $permissao = true;
}else {
  $permissao = false;
}
  • What did you try to do? What did you get? What do you know about PHP?

  • This is the return of the database permissions. I need in the programming to check if the user has certain permission, for this I use in_array. Regarding PHP I am beginner.

  • Right, but have you tried the conversion you want? What was the result obtained? Error? Could you [Dit] the question and add your attempt?

  • I tried to do yes. I changed in fetchAll PDO (PDO::FETCH_ASSOC) to fetchAll(PDO::FETCH_OBJ) by adding Return $rs ->DESCRICAO.

  • Place in the question the code you tried to do and describe what happened, please.

  • I tried too, playing the variable in the foreach catching only the value, and nothing tbm.

  • That array $rs comes from the bank? uses PDO to retrieve the information?

  • 1

    It really was duplicate. The array_map solved it. Thank you Anderson Calors Woss

Show 3 more comments

1 answer

1

You can format (Flatten) this array with PDO the first step is your query should return only two fields being the first the id (array key) and the second the value. When retrieving data use constant PDO::FETCH_KEY_PAR in fetch()/fetchAll()

The array that would normally be:

Array
(
    [0] => Array
        (
            [id] => 1
            [descricao] => new
        )

    [1] => Array
        (
            [id] => 2
            [descricao] => edit
        )

    [2] => Array
        (
            [id] => 3
            [descricao] => delete
        )

    [3] => Array
        (
            [id] => 4
            [descricao] => update
        )

)

Vira:

Array
(
    [1] => new
    [2] => edit
    [3] => delete
    [4] => update
)

Code is as follows (with a small optimization)

$rs = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$acao = 'editar';
$permissao = in_array($acao ,$rs, true);

Browser other questions tagged

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