我有一个数据库查询结果,它是一个数组,如下所示:
[{"uid":29,"totalAmount":"5400.00"},
{"uid":499,"totalAmount":"5400.00"},
{"uid":507,"totalAmount":"3960.00"},
{"uid":497,"totalAmount":"3960.00"},
{"uid":498,"totalAmount":"3960.00"},
{"uid":34,"totalAmount":"3960.00"},
{"uid":21,"totalAmount":"3240.00"},
{"uid":27,"totalAmount":"2880.00"},
{"uid":500,"totalAmount":"2880.00"},
{"uid":19,"totalAmount":"2700.00"},
{"uid":22,"totalAmount":"2700.00"},
{"uid":20,"totalAmount":"2520.00"},
{"uid":23,"totalAmount":"2520.00"},
{"uid":504,"totalAmount":"1800.00"},
{"uid":496,"totalAmount":"1440.00"},
{"uid":26,"totalAmount":"1260.00"},
{"uid":491,"totalAmount":"1080.00"},
{"uid":492,"totalAmount":"720.00"},
{"uid":464,"totalAmount":"540.00"},
{"uid":493,"totalAmount":"540.00"},
{"uid":76,"totalAmount":"540.00"},
{"uid":505,"totalAmount":"180.00"},
{"uid":506,"totalAmount":"180.00"},
{"uid":494,"totalAmount":"180.00"},
{"uid":495,"totalAmount":"180.00"}]
从这个结果我想创建一个多维数组,如下所示:
[
"0" =>
[
"0"=>["uid"=>29, "totalAmount"=>5400 ],
"1"=>["uid"=>499, "totalAmount"=>5400]
],
"1" =>
[
"0"=>["uid"=>507, "totalAmount"=>3960 ],
"1"=>["uid"=>497, "totalAmount"=>3960],
"2"=>["uid"=>498, "totalAmount"=>3960 ],
"3"=>["uid"=>34, "totalAmount"=>3960],
],
]
// and so on ...
我尝试过foreach
:
$topEar = [];
$amount = '';
foreach( $topEarners as $te)
{
array_push($topEar, [$te->uid=>$te->totalAmount]);
}
$topEar;
答案 0 :(得分:0)
您可以这样做:
$topEar = array();
$currAmountArray = array();
$amount = null;
foreach( $topEarners as $te) {
if( !is_null($amount) && $te->totalAmount != $amount ) {
array_push($topEar, $currAmountArray);
$currAmountArray = array();
}
array_push($currAmountArray, $te);
$amount = $te->totalAmount;
}
if( !empty($currAmountArray) ) {
array_push($topEar, $currAmountArray);
}
print_r($topEar);
您在每次迭代中保存最后$totalAmount
并且只要它没有更改 - 当$currAmountArray
更改您时,您将值存储在名为$totalAmount
的子数组中将值推送到主数组。
我还在foreach
循环后添加了一个条件,以确保$currAmountArray
中的最后一批数据也会被推送到主数组($topEar
)。
答案 1 :(得分:0)
如果使用SQL无法获得所需的结构,那么这将是PHP中最简单的方法:
$topEarners = json_decode($json, true);
foreach($topEarners as $row) {
$result[$row['totalAmount']][] = $row;
}
totalAmount
作为键如果您想重置密钥:
$result = array_values($result);