gpt4 book ai didi

php - 操作数组中的数据

转载 作者:行者123 更新时间:2023-11-29 20:48:21 25 4
gpt4 key购买 nike

我正在开发一个混合移动应用程序。在客户端,我使用 html、css ajax/jquery。在服务器端(第三方)我使用 PHP MySql。现在,当用户(应用程序)向服务器发送ajax请求时,服务器将以json格式发回详细信息。但在发送json数据之前,我想先操作数组中的数据或添加数组中的数据。

这是服务器发送的示例 json 数据。

[{
"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"
}]

这是我的 PHP 代码。

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

如何操作数据库中的数组。

  1. 格式和条件:我想更改所有"profit":null。如果利润“为空”,则回显“n/a”,否则回显金额(使用数字格式)。以及 "date_open":"2015-01-04" 将其格式化为 Y-M-dd。

  2. 计算:使用 "id":"11" 将另一个字段添加到第一个数组的数组示例中。我想添加另一个字段,例如总计,即总计 = 投资 + 利润(如果不为空)。

我想在 php 服务器上执行此操作,因为对我来说格式化和操作数据比在客户端更容易。因此,当我在服务器端完成此操作时,json 数据已经设置并准备好显示。 我更喜欢使用 php 而不是 mysql 查询。谢谢。

更新#1:我现在可以操作/更改 foreach 循环内的数组。我现在的问题是如何在数组中添加数据。例如用户投资总额。我在循环 total_investment=0 之前添加了此代码,然后在循环内添加了 total_investment += user_product['investment'];

应该显示如下:

[{
"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?
}]

最佳答案

在 SQL 中,我会做类似的事情:

SELECT 
id,user_id,product,quantity,
DATE_FORMAT(date_open,'%Y-%m-%d'),
paid,harvested,reinvest,
if (profit IS NULL,'n/a',FORMAT(profit,'de_DE')) as profit,
investment,
if (profit IS NOT NULL, investment+profit, NULL ) as total
FROM user_products
WHERE uproducts_user_id = '{$userid}'

关于php - 操作数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38259039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com