如何优秀的php开发人员会解决这个问题?
我花了很多时间想办法如何缩短二维数组。
$expanded = [ [1, 1], [1, 4], [3, 5], [1, 3], [4, 1], [4, 2], [1, 2], [4, 7], [3, 5] ];
进入:
$shortened = [ [1, 10], [4, 10], [3, 10];
我想要的是,如果两个数组的第一个值相同,请合并它们!
这就是让我最接近我想要的东西:
$expanded = [ [1, 1], [1, 4], [3, 5], [1, 3], [2, 1], [2, 2], [1, 2], [2, 7], [3, 5] ];
$len = count($expanded);
$shortened[0] = $expanded[0];
for ($i = 0; $i < $len; $i++) {
for ($j = 1; $j < $len-$i; $j++) {
if ($expanded[$i][0] == $expanded[$i+$j][0]) {
$shortened[$i][0] = $expanded[$i][0];
$shortened[][1] = $shortened[$i][1] + $expanded[$i+$j][1];
} else {
$shortened[$i+1] = $expanded[$i+$j];
}
}
}
答案 0 :(得分:1)
$shortened = array_reduce(
$expanded,
function (array $carry, array $item) {
list($one, $two) = $item;
if (! isset($carry[$one])) {
$carry[$one] = [ $one, 0 ];
}
$carry[$one][1] += $two;
return $carry;
},
[]
);
答案 1 :(得分:0)
我在几分钟内就完成了这件事:
$expanded = [ [1, 1], [1, 4], [3, 5], [1, 3], [4, 1], [4, 2], [1, 2], [4, 7], [3, 5] ];
foreach ($expanded as $part)
{
$temp[$part[0]] += $part[1];
}
foreach ($temp as $key => $value)
{
$shortened[] = [$key, $value];
}
echo '<pre>';
print_r($shortened);
echo '</pre>';
这是我真正使用的版本,因为我的PHP&lt; 5.4:
$expanded = array(array(1, 1),
array(1, 4),
array(3, 5),
array(1, 3),
array(4, 1),
array(4, 2),
array(1, 2),
array(4, 7),
array(3, 5));
foreach ($expanded as $part)
{
$temp[$part[0]] += $part[1];
}
foreach ($temp as $key => $value)
{
$shortened[] = array($key, $value);
}
echo '<pre>';
print_r($shortened);
echo '</pre>';
短片版本如下:
foreach ($expanded as $p) $t[$p[0]] += $p[1];
foreach ($t as $k => $v) $shortened[] = [$k,$v];