0

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?

2
  • 3
    The expected result isn't valid JSON. Instead of {"26", "180"}, don't you mean ["26", "180"]? Commented Jan 10, 2022 at 7:27
  • What have you tried so far? Is there any rule behind this formatting? Commented Jan 10, 2022 at 7:56

3 Answers 3

1

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}
]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.