我已经使用csv文件创建了多维数组。 我得到以下数组:
Array
(
[0] => Array
(
[0] => Product
[1] => Price
[2] => Quantity
[3] => Date
)
[1] => Array
(
[0] => Teddybear
[1] => 3.789,33
[2] => 2
[3] => 2018-08-14
)
[2] => Array
(
[0] => Teddybear
[1] => 2.702,17
[2] => 1
[3] => 2018-02-17
)
[3] => Array
(
[0] => Table
[1] => 2.932,29
[2] => 5
[3] => 2018-10-09
)
[4] => Array
(
[0] => Lamp
[1] => 671,70
[2] => 3
[3] => 2018-12-11
)
[5] => Array
(
[0] => Teddybear
[1] => 481,21
[2] => 3
[3] => 2018-03-24
)
[6] => Array
(
[0] => Table
[1] => 456,52
[2] => 3
[3] => 2018-05-14
)
[7] => Array
(
[0] => Chair
[1] => 2.960,20
[2] => 2
[3] => 2018-06-20
)
[8] =>
)
我需要创建一个json文件,但在此之前,我需要计算每月的所有产品和营业额
我是PHP的新手/初级开发人员,而且我更擅长WordPress,所以请原谅我的错误代码和/或错误做法。我在这里学习。
我真的不知道如何选择所有的泰迪熊。我知道我可以$csv[1][1];
为第一个Tedybear选择营业额。
答案 0 :(得分:1)
好的,这里应该有您需要的所有东西,我做了3个函数,您可以将它们链接在一起以获得所需的东西,如示例中
$data=[
["Product","Price","Quantity","Date"], // <-- if you want to remove the header remove all the lines with this symbol *
["Teddybear",3789.33,2,"2018-08-14"],
["Teddybear",2702.17,1,"2018-02-17"],
["Table",2932.29,5,"2018-10-09"],
["Lamp",671.70,3,"2018-12-11"],
["Teddybear",481.21,3,"2018-03-24"],
["Table",45.52,3,"2018-05-14"],
["Chair",2960.20,2,"2018-06-20"]
];
function WhereFromColum($data,$colum,$equal){
$ret=[];
array_push($ret,$data[0]); // *
$colum = is_numeric($colum)?$colum:array_search($colum,$data[0]);
for($i=1/* 0 if you remove the header to data*/;$i!=count($data);$i++)
if ($data[$i][$colum]==$equal)
array_push($ret,$data[$i]);
return $ret;
}
function CountFromColum($data,$colum){
$ret=0;
$colum = is_numeric($colum)?$colum:array_search($colum,$data[0]);
for($i=1/* 0 if you remove the header to data*/;$i!=count($data);$i++)
$ret+=$data[$i][$colum];
return $ret;
}
function WhereFromColumData($data,$colum,$min,$max){
$contractDateBegin = new DateTime($min);
$contractDateEnd = new DateTime($max);
$ret=[];
array_push($ret,$data[0]); // *
$colum = is_numeric($colum)?$colum:array_search($colum,$data[0]);
for($i=1/* 0 if you remove the header to data*/;$i!=count($data);$i++){
$paymentDate = new DateTime($data[$i][$colum]);
if ($paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() &&
$paymentDate->getTimestamp() < $contractDateEnd->getTimestamp())
array_push($ret,$data[$i]);
}
return $ret;
}
var_dump(WhereFromColum($data,"Product","Teddybear")); // get all Teddybear's Product
var_dump(CountFromColum($data,"Quantity")); // get all Quantity
var_dump(CountFromColum(WhereFromColum($data,"Product","Teddybear"),"Quantity")); // get all Quantity of Teddybear's Product
var_dump(WhereFromColumData($data,"Date","2018-08-01","2018-12-01")); // get all between 2018-08-01 and 2018-12-01
var_dump(WhereFromColumData(WhereFromColum($data,"Product","Teddybear"),"Date","2018-08-01","2018-12-01")); // get all Teddybear's Product between 2018-08-01 and 2018-12-01
通常,我通常不编写代码,而是解释如何执行代码,但是在您的情况下,它太复杂了,因此请仔细阅读这三个功能,并尝试了解它们的工作原理。 PHP我建议您使用这些功能,并对其进行修改以适合您的最佳需求。当您了解它们的工作原理后,您还可以创建具有相同嵌套逻辑的另一个过滤器,从而使您可以制作更高级的过滤器。