我有这个多维数组:
$sales = Array (
[0] => Array (
[salesID] => 1
[price] => 50
[user_first] => Jane
[user_last] => Doe
)
[1] => Array (
[salesID] => 2
[price] => 250
[user_first] => John
[user_last] => Smith
)
[2] => Array (
[salesID] => 1
[price] => 50
[user_first] => Jane
[user_last] => Doe
)
);
我需要变成:
$sales = Array(
[2] => Array (
[Name] => John Smith
[Sales] => 250
[Signups] => 1
)
[1] => Array (
[Name] => Jane Doe
[Sales] => 100
[Signups] => 2
)
);
我目前已经创建了新数组,但它并没有更新新数组中的值。
$leader_board = array();
foreach ($sales as $index => $row) {
if (!in_array($row['salesID'], $leader_board)) {
$new_row = array('Name' => $row['user_first'] . ' ' . $row['user_last'], 'SignUps' => 1, 'Sales' => $row['price']);
$leader_board[$row['salesID']] = $new_row;
} else {
$leader_board[$row['salesID']]['SignUps'] += 1;
$leader_board[$row['salesID']]['Sales'] += $row['price'];
}
}
答案 0 :(得分:1)
您可以像下面这样做(我根据您的输入和预期输出给出答案, 不是基于您尝试的代码 强>): -
$final_array = array();
foreach($sales as $sale){
$final_array[$sale['id']]['Name'] = $sale['user_first']." ".$sale['user_last'];
$final_array[$sale['id']]['Sales'] = (isset($final_array[$sale['id']]['Sales'])) ? $final_array[$sale['id']]['Sales']+ $sale['price'] : $sale['price'];
$final_array[$sale['id']]['Signups'] = (isset($final_array[$sale['id']]['Signups'])) ? $final_array[$sale['id']]['Signups']+ 1 : 1;
}
krsort($final_array);// Sort array by key in reverse order
print_r($final_array);
输出: - https://eval.in/870767
参考: - krsort()