Skip to content
Advertisement

how to fix this php json response?

I get this result from my PHP:

{“risultato”:”1″,”ris”:[{“pda”:”763,41″,”num1″:”86,86″,”num2″:”21,18″,”num3″:”178603,201535″}]}

What I need to do if I want to return the result like this instead?

{“risultato”:”1″,”ris”:[{“pda”:”763″,”num1″:”86″,”num2″:”21″,”num3″:”178603″},{“pda”:”41″,”num1″:”86″,”num2″:”18″,”num3″:”201535″}]}

Here is my PHP code:

$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();
    
    $result=array("risultato"=>"1", "ris"=>"");
    while($rispostacarte=$risultatocarte->fetch_assoc()){
    
    $result['ris']=array($rispostacarte);
    echo json_encode($result);
                  
    }
    $stmtcarte->close();

Advertisement

Answer

I am SURE there is a Mysql approach to your problem, and therefore, definitely, any other direction is not the best idea. But still, I prefer a PHP snippet to get your desired response.

Let’s say you have got the $result variable exactly as like the way you showed in your question. Here is what I came up with:

<?php
$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;
print_r($result);
?>

The result will be:

Array
(
    [risultato] => 1
    [ris] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [pda] => 763
                            [num1] => 86
                            [num2] => 21
                            [num3] => 178603
                        )

                    [1] => Array
                        (
                            [pda] => 41
                            [num1] => 86
                            [num2] => 18
                            [num3] => 201535
                        )

                )

        )

)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement