任何人都知道如何动态地获得$ initial_array $ wanted_array? 谢谢!
// $initial_array
Array
(
[0] => Array
(
[thingy] => 4
[date] => 27/11/2013
)
[1] => Array
(
[thingy] => 4
[date] => 27/11/2013
)
[2] => Array
(
[thingy] => 2
[date] => 27/11/2015
)
[3] => Array
(
[thingy] => 2
[date] => 27/11/2015
)
[4] => Array
(
[thingy] => 2
[date] => 27/11/2015
)
)
// $wanted_array
// The quantity key will count instances that array item in $initial_array
Array
(
[0] => Array
(
[thingy] => 4
[date] => 27/11/2013
[quantity] = 2
)
[1] => Array
(
[thingy] => 2
[date] => 27/11/2015
[quantity] = 3
)
答案 0 :(得分:1)
我把它分解为两步。
根据日期排列数据并将结果存储在$ result变量中。
$result = array();
foreach($array as $arr) {
$result[$arr['date']][] = $arr;
}
这给出了:
Array
(
[27/11/2013] => Array
(
[0] => Array
(
[thingy] => 4
[date] => 27/11/2013
)
[1] => Array
(
[thingy] => 4
[date] => 27/11/2013
)
)
[27/11/2015] => Array
(
[0] => Array
(
[thingy] => 2
[date] => 27/11/2015
)
[1] => Array
(
[thingy] => 2
[date] => 27/11/2015
)
[2] => Array
(
[thingy] => 2
[date] => 27/11/2015
)
)
)
循环遍历数组并根据我们的需要对其进行格式化。请注意,子数组长度表示数量。
foreach($result as $res) {
$final[] = array_merge(
current($res),
array("quantity" => count($res))
);
}
输出:
Array
(
[0] => Array
(
[thingy] => 4
[date] => 27/11/2013
[quantity] => 2
)
[1] => Array
(
[thingy] => 2
[date] => 27/11/2015
[quantity] => 3
)
)