Home > Mobile >  how to remove extra square bracket in json format?
how to remove extra square bracket in json format?

Time:01-28

this is my json response:

{"risultato":"1","ris":[[{"pda":"788","num1":"83","num2":"10","num3":"207410"},{"pda":"232","num1":"83","num2":"14","num3":"204935"}]]}

as you can see there is an extra square bracket, how can I remove it? the result I would like this:

{"risultato":"1","ris":[{"pda":"788","num1":"83","num2":"10","num3":"207410"},{"pda":"232","num1":"83","num2":"14","num3":"204935"}]}

php:

$stmtcarte = $connection->prepare("SELECT GROUP_CONCAT(concat.pda) as pda, GROUP_CONCAT(concat.num1) as num1,GROUP_CONCAT(concat.num2) as num2, GROUP_CONCAT(concat.num3) as num3 FROM (SELECT pda, num1, num2, num3 FROM giocatori WHERE categoria=? ORDER BY RAND() LIMIT 2 ) concat");

        $categoria=$categoriaselezionata;
        $stmtcarte->bind_param("s",$categoria);
        $stmtcarte->execute();
        $risultatocarte = $stmtcarte->get_result();
        $numero_giocatori = $risultatocarte->num_rows;
        $result=array("risultato"=>"1", "ris"=>"");
        while($rispostacarte=$risultatocarte->fetch_assoc()){

              $result['ris']=array($rispostacarte);
              $ris = $result["ris"][0];
              $tempRis = [];
              foreach ($ris as $key => $value) {
              $explodedArray = explode(",", $value);
              $length = count($explodedArray);
              for ($i=0; $i < $length ; $i  ) { 
              $tempRis[$i][$key] = $explodedArray[$i];
    }
}
            $result["ris][0] = $tempRis;
            echo json_encode($result);
            
              
        }
        $stmtcarte->close();

CodePudding user response:

You can use simple code like:

<?php

$query = "SELECT pda, num1, num2, num3 
        FROM giocatori WHERE categoria=? 
        ORDER BY RAND() 
        LIMIT 2";

// get DB data using PDO
$stmt = $pdo->prepare($query);
$stmt->execute([$category]);

$risultato = [
    'risultato' => 1,
    'ris'=>[]
];

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $risultato['ris'][] = $row;
}

print_r(json_encode($risultato, JSON_PRETTY_PRINT));

Test PHP & MySQL code here

Result:

{
    "risultato": 1,
    "ris": [
        {
            "pda": "788",
            "num1": "83",
            "num2": "10",
            "num3": "207410"
        },
        {
            "pda": "232",
            "num1": "83",
            "num2": "14",
            "num3": "204935"
        }
    ]
}

CodePudding user response:

If the String Length Of the JSON Response is Static, You Can Remove the extra bracket easily by removing the character index of the character and replacing it with a '', which in your case will be 25:

$str = '{"risultato":"1","ris":[[{"pda":"788","num1":"83","num2":"10","num3":"207410"},{"pda":"232","num1":"83","num2":"14","num3":"204935"}]]}
';
$str[25] = '';

echo $str;
  •  Tags:  
  • Related