Organizing Response Array

2

How to organize array index of 2nd dimension?

Search

  $stmt = getConn()->query("SELECT hash,id,quantidade FROM pergaminhos");
  $resp = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN);

response

Array
(
    [1] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [2] => Array
        (
            [0] => 4
        )
)

desired response

Array
(
    [1] => Array
        (
            [1] => 1
            [2] => 1
            [3] => 1
        )

    [2] => Array
        (
            [4] => 1
        )
)

Written form for better understanding

Array
(
    [valor_do_hash] => Array
        (
            [valor_do_id] => valor_do_quantidade
            [valor_do_id] => valor_do_quantidade
            [valor_do_id] => valor_do_quantidade
        )

    [valor_do_hash] => Array
        (
            [valor_do_id] => valor_do_quantidade
        )
)
    
asked by anonymous 22.06.2018 / 08:34

2 answers

2
$stmt = getConn()->query("SELECT hash,id,quantidade FROM pergaminhos");
$resp = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN);

$novaResp = array();

foreach ($resp as $linha) {
    $novaResp[$linha[0]][$linha[1]] = $linha[2];
}

print_r($novaResp);
    
22.06.2018 / 13:25
2

Use the array_map function to cycle through the array and apply a function to each element traversed:

$Resposta = array_map(function($Valor) {
  // Faz alguma coisa com "$Valor"
}, $Resposta);

use the array_values function to get all values of the current element " $Valor ":

$Chaves = array_values($Valor);

Then, use the array_fill_keys function to create an array, the values of $Chaves as indexes and 1 as value of each element of that array:

return array_fill_keys($Chaves, 1);

Soon, the complete code:

$Resposta = [
  1 => [
    0 => 1,
    1 => 2,
    2 => 3,
  ],
  2 => [
    0 => 4
  ]
];
$Resposta = array_map(function($Valor) {
  $Chaves = array_values($Valor);
  return array_fill_keys($Chaves, 1);
}, $Resposta);

If you give a print_r it will output:

Array
(
  [1] => Array
  (
    [1] => 1
    [2] => 1
    [3] => 1
  )

  [2] => Array
  (
    [4] => 1
  )
)

See working at repl.it

References

22.06.2018 / 09:04