I have an array with values like:
$menuArray = [
[
'parent' => 'Basic',
'parentId' => 1,
'child' => 'Birthday',
'childId' => 2,
],
[
'parent' => 'Basic',
'parentId' => 1,
'child' => 'Gender',
'childId' => 3,
],
[
'parent' => 'Geo',
'parentId' => 10,
'child' => 'Current City',
'childId' => 11,
],
[
'parent' => 'Known me',
'parentId' => 5,
'child' => 'My personality',
'childId' => 7,
],
[
'parent' => 'Known me',
'parentId' => 5,
'child' => 'Best life moment',
'childId' => 8,
],
];
And I want to group this array on parent (or parentId) and the final result would be like:
[
[
'parent' => 'Basic',
'parentId' => 1,
'child' => ['Birthday', 'Gender'],
],
[
'parent' => 'Geo',
'parentId' => 10,
'child' => ['Current City'],
],
[
'parent' => 'Known me',
'parentId' => 5,
'child' => ['My personality', 'Best life moment'],
],
]
My current code:
$filter = [];
$f = 0;
for ($i = 0; $i < count($menuArray); $i++) {
$c = 0;
for ($b = 0; $b < count($filter); $b++) {
if ($filter[$b]['parent'] == $menuArray[$i]['parent']) {
$c++;
}
}
if ($c == 0) {
$filter[$f]['parent'] = $menuArray[$i]['parent'];
$filter[$f]['parentId'] = $menuArray[$i]['parentId'];
$filter[$f]['child'][] = $menuArray[$i]['child'];
$f++;
}
}
But it doesn't push child values from subsequent encounters of a parent-related row into the result array.
c++you should also sayfilter[$b]['child'][] = $menuArray[$i]['child']