我是PHP的新手,我在我的项目中发现了这个问题。 我有这个数组:
Array
(
[0] => Array
(
[count] => 1
[account] => 14
[amt] => 1000
)
[1] => Array
(
[count] => 1
[account] => 11
[amt] => 124
)
[2] => Array
(
[count] => 1
[account] => 12
[amt] => 2345
)
[3] => Array
(
[count] => 1
[account] => 14
[amt] => 2345
)
)
我希望将其转换为此格式
Array
(
[14] => Array
(
[0] => Array
(
[amt] => 1000
[count] => 1
[volume] => 1000
)
[1] => Array
(
[amt] => 124
[count] => 0
[volume] => 0
)
[2] => Array
(
[amt] => 2345
[count] => 1
[volume] => 2345
)
)
[11] => Array
(
[0] => Array
(
[amt] => 1000
[count] => 0
[volume] => 0
)
[1] => Array
(
[amt] => 124
[count] => 1
[volume] => 124
)
[2] => Array
(
[amt] => 2345
[count] => 0
[volume] => 0
)
)
[12] => Array
(
[0] => Array
(
[amt] => 1000
[count] => 0
[volume] => 0
)
[1] => Array
(
[amt] => 124
[count] => 0
[volume] => 0
)
[2] => Array
(
[amt] => 2345
[count] => 1
[volume] => 2345
)
)
)
您可能会注意到account
键成为新数组的键,值内的数组包含第一个数组上的所有数组。请帮忙。它就像一个硬核阵列,我真的需要它用于我的项目。谢谢!
答案 0 :(得分:1)
试试这个:
$newArray = array();
foreach ($origArray as $val)
{
$val['volume'] = $val['count'] * $val['amt'];
$account = $val['account'];
unset($val['account']);
$newArray[$account][]=$val;
}
修改强>
好吧我想也许这就在你想要的地方附近,虽然我不明白为什么每个帐户有3个结果,当有4个开始时。
$newArray = array();
$accounts = array();
foreach ($origArray as $val) {
$accounts[$val['account']] = $val['account'];
}
foreach ($accounts as $account) {
foreach ($origArray as $val) {
$val['count'] = $account == $val['account'] ? $val['count'] : 0;
$val['volume'] = $val['count'] * $val['amt'];
unset($val['account']);
$newArray[$account][] = $val;
}
}
答案 1 :(得分:0)
<?php
$final_array = array();
$dataset = YOUR FIRST ARRAY;
foreach($dataset as $data)
{
$account = $data['account'];
unset($data['account'])
$final_array[$account][] = $data;
}
这应该做你需要的。虽然我不知道你的第二个数组中的音量来自何处