我有一个“ Javascript减少”代码,我们在其中打印一次具有相同值的元素。
var array = [[1, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]];
result = array
.reduce((r, a) => {
var o = a.reduce((p, id) => {
var temp = p.subCategories.find(q => q.id === id);
if (!temp) {
p.subCategories.push(temp = { id, subCategories: [] });
}
return temp;
}, r);
o.count = (o.count || 0) + 1;
return r;
}, { subCategories: [] })
.subCategories;
console.log(result);
我想将其转换为php。我尝试了下面的代码。
$categories = [
[1, 2, 3, 5],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]
]
$result = array_reduce($categories, function ($r, $a) {
$o = array_reduce($a, function ($p, $id) {
if (isset($p['subCategories']))
$temp = array_search($id, array_column($p['subCategories'], 'id'));
else
$temp = false;
if (!$temp) {
$obj = (object)array(
'id' => 0,
'subCategories' => array()
);
$p['subCategories'] = array();
array_push($p['subCategories'], $obj);
} else {
$temp = $p['subCategories'][$temp];
}
return $temp;
}, $r);
$o->count = 0;
$o->count = $o->count + 1;
return $r;
});
return $result;
我在计算部分遇到了问题,但无法正常工作。我在哪里可以错?