我有一个数组,我想在其上添加另一个数组。目前,服务器(php)将此数组作为json数据进行响应。这是样本。
$ip = getRequestIP();
$cf = isCloudflare();
if($cf) echo "Cloudflare :D<br>";
else echo "Not cloudflare o_0";
echo "Your actual ip address is: ". $ip;
然后这里的代码就在这里。
[{
"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"
}]
现在我想添加一个数组,它是用户投资的总和。所以我认为代码是这样的:
$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);
所以上面的代码,我怎样才能实现这一点,以便服务器响应如下:
$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;
答案 0 :(得分:2)
有很多方法,但试试这个:
$server_msg = $product;
array_push($server_msg, array('total_investment' => $total_product));
这应该可以为您提供所需的输出。
答案 1 :(得分:2)
如果您正在处理API(看起来似乎如此),我建议您将JSON的结构重新构建为:
{
"items": [{
"id":"11",
"user_id":"8000",
"product":"Shoes A",
"quantity":"1",
"date_open":"2015-01-04",
"paid":"1",
"harvested":"",
"reinvest":null,
"profit":null,
"investment":"3000"
}, ....],
"total_investment": 45000
}
要回答您的问题,@ rexmac建议是一种方式。但是,您可能不希望混淆响应字段。如果你这样结束,肯定在客户端是丑陋的:(假设是Javascript)
for (let i = 0; i < data.length; i++) {
if (typeof data[i].total_investment !== "undefined") {
totalInvestment = data[i].total_investment;
//....
}
//....
}
但是(方式更冷):
let totalInvestment = data.total_investment;
for (let i = 0; i < data.items.length; i++) {
//....
}
希望这有帮助。