Skip to content
Advertisement

How to push custom key and value into an array from an associative array in PHP

Take a look at this loop

JavaScript

My table,

id date income expense
1 2022-05-01 00:00:00 20 10
2 2022-06-01 00:00:00 40 30
3 2022-07-01 00:00:00 60 50

In desire one, I want to push custom key and value with specific columns from an associative array ($row) like this,

JavaScript

In also desire two,

JavaScript

Final output is like below,

JavaScript
JavaScript

I will echo with json_encode,

echo json_encode($dataPoints1);

echo json_encode($dataPoints2);

Advertisement

Answer

Better variable naming would help to make your code more clear.

Mysqli resultset objects can be iterated with foreach() as if they are arrays of associative arrays.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement