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:

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

Please tell me how to achieve this?

Upvotes: 0

Views: 80

Answers (3)

ikhvjs
ikhvjs

Reputation: 5937

Beside other answer,

I usually use array_map for this kind of array transformation.

$result = [['id' => 1, 'summ' => 2], ['id' => 3, 'summ' => 4], ['id' => 5, 'summ' => 6]];

$output = array_map(function ($item) {
    return [$item['id'], $item['summ']];
}, $result);

Upvotes: 1

M. Eriksson
M. Eriksson

Reputation: 13635

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"],
    ...
]

Upvotes: 1

behzad m salehi
behzad m salehi

Reputation: 1076

check this :

foreach($result as $row)
   $array[] = ['id'=>$row["id"], 'summ'=>$row["summ"]];
echo json_encode($array);

for example if your $result contains such a array :

$result    = [['id'=>1, 'summ'=>2] , ['id'=>3, 'summ'=>4] , ['id'=>5, 'summ'=>6]];  

the scripts output will be :

[
    {"id":1,"summ":2},
    {"id":3,"summ":4},
    {"id":5,"summ":6}
]

Upvotes: 1

Related Questions