Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to form Json array from sql pdo data in php?

The code that I have does not display what I need, tell me what I’m doing wrong

   $new_array =[];
  foreach($result as $row)
   {
    $array =[
        'id'=> $row["id"],
        'summ' => $row["summ"],
    ];
    foreach($array AS $key => $val) {
     $new_array[] = $val;
    }
   }
   echo json_encode($new_array);

Outputs the following result

["26","180","25","35","24","50","23","50","22","100"]

But I need the result to be different, and I can’t.
Here’s an example of how it should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
{"26","180"},
{"25","35"},
{"24","50"},
{"23","50"},
{"22","100"}
]

Please tell me how to achieve this?

>Solution :

You can skip the inner loop:

$new_array = [];

foreach($result as $row)
{
    $new_array[] = [
        $row['id'],
        $row['summ']
    ];
}

echo json_encode($new_array);

That should give you the result:

[
    ["26","180"],
    ["25","35"],
    ...
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading