c.k c.k - 4 months ago 17
PHP Question

Add data as an array

I have an array which I want to add another array on it. Currently the server (php) respond this array as json data. Here is the sample.

[{
"id":"11",
"user_id":"8000",
"product":"Shoes A",
"quantity":"1",
"date_open":"2015-01-04",
"paid":"1",
"harvested":"",
"reinvest":null,
"profit":null,
"investment":"3000"
},

{
"id":"12",
"user_id":"8000",
"product":"Shoes B",
"quantity":"1",
"date_open":"2015-03-01",
"paid":"1",
"harvested":"",
"reinvest":null,
"profit":200,
"investment":"1500"
}]


Then the code of this is here.

$userid = $_POST['user'];
$sql = "SELECT * FROM user_products WHERE uproducts_user_id = '{$userid}'";
$user_products = db::select($sql);

$product = array();
foreach( $user_products as $user_product){
array_push($product, $user_product);
}

$server_msg = $product;

echo json_encode($server_msg);


Now I want to add an array which is the sum of user invesment's. So I'm thinking the code would be like this:

$product = array();
$total_product= 0;
foreach($user_products as $user_product){
$total_product+= $user_product['investment']; // the sum of investment how to show this as an array?

array_push($product, $user_product);

}
$server_msg = $product;


So the above code, how can I achieve this so that the server response would be like this:

[{
"id":"11",
"user_id":"8000",
"product":"Shoes A",
"quantity":"1",
"date_open":"2015-01-04",
"paid":"1",
"harvested":"",
"reinvest":null,
"profit":null,
"investment":"3000"
},

{
"id":"12",
"user_id":"8000",
"product":"Shoes B",
"quantity":"1",
"date_open":"2015-03-01",
"paid":"1",
"harvested":"",
"reinvest":null,
"profit":200,
"investment":"1500"
},
{
"total_investment":"4500" // how can I add this here?
}]

Answer

There are many ways, but try this:

$server_msg = $product;
array_push($server_msg, array('total_investment' => $total_product));

That should give you the output you desire.

Comments