Object for Array php

0

Hello, I have a problem, this code below is returning a 'type' object, I need 'type' to be array.

while ($obj = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $stmt2 = $db->query('SELECT * FROM wines a, uva b WHERE a.id_tipo = '.$obj['idtipo'].' AND a.id_uva = b.id GROUP BY a.id_uva');
       while ($obj2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
             $wines[$obj['tipo']][] = $obj2;
       }

}

It returns like this

{"ESPUMANTES": [
    {
        "id": "5",
        "name": "MIOLO MILESSIME",
        "uva": "BRUT"
    },

],
"VINHOS BRANCOS": [
    {
        "id": "1",
        "name": "CASA VALDUGA LEOPOLDINA GRAN RESERVA",
        "uva": "CHARDONNAY"
    },

]}

I need "SPARKLES" and "WHITE WINES" to be inside an array.

{
[
   1: "ESPUMANTES" [
        {
            "id": "1",
            "name": "CASA VALDUGA LEOPOLDINA GRAN RESERVA",
            "uva": "CHARDONNAY"
        }
    ] 
],
[
    2: "VINHOS BRANCOS" [
        {
            "id": "1",
            "name": "CASA VALDUGA LEOPOLDINA GRAN RESERVA",
            "uva": "CHARDONNAY"
        }
]

}

    
asked by anonymous 04.05.2018 / 22:17

4 answers

1

Try this:

$x = 0;
while ($obj = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $stmt2 = $db->query('SELECT * FROM wines a, uva b WHERE a.id_tipo = '.$obj['idtipo'].' AND a.id_uva = b.id GROUP BY a.id_uva');
    while ($obj2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
        $wines[$x][$obj['tipo']] = $obj2;
    }
    $x++;
}
    
05.05.2018 / 00:25
0

It looks like a JSON this data

Try:

$array = json_decode($objeto, true);

link

    
04.05.2018 / 22:27
0

Patrick, if you do not have the need to be inside the PHP transformation to array, you can do it as follows.

Where I assign the value to x would be the response of your server.

let x = {
"ESPUMANTES": [
    {
        "id": "5",
        "name": "MIOLO MILESSIME",
        "uva": "BRUT"
    }
],
"VINHOS BRANCOS": [
    {
        "id": "1",
        "name": "CASA VALDUGA LEOPOLDINA GRAN RESERVA",
        "uva": "CHARDONNAY"
    }
],
"VINHOS TINTOS": [
    {
        "id": "4",
        "name": "ERRAZURIZ 1870 RESERVA CARMENERE ",
        "uva": "CARMENERE"
    }
]
};

let z = Object.values(x);
z.forEach(res => { console.log(res) }); 
    
05.05.2018 / 00:21
-1

Two things can be done:

  • Typecast

    $ wines [$ obj ['type']] [] = (array) $ obj2;

  • Use json_decode

    json_decode ($ wines, true)

  • 04.05.2018 / 22:28