Array filteration PHP
- by Muhammad Sajid
I have an array with values like:
Array
(
[0] => Array
(
[parent] => Basic
[parentId] => 1
[child] => Birthday
[childId] => 2
)
[1] => Array
(
[parent] => Basic
[parentId] => 1
[child] => Gender
[childId] => 3
)
[2] => Array
(
[parent] => Geo
[parentId] => 10
[child] => Current City
[childId] => 11
)
[3] => Array
(
[parent] => Known me
[parentId] => 5
[child] => My personality
[childId] => 7
)
[4] => Array
(
[parent] => Known me
[parentId] => 5
[child] => Best life moment
[childId] => 8
)
)
And I want to filter this array such that their filtration based on parent index, and the final result would be like:
Array
(
[0] => Array
(
[parent] => Basic
[parentId] => 1
[child] => Array
(
[0] => Birthday
[1] => Gender
)
)
[1] => Array
(
[parent] => Geo
[parentId] => 10
[child] => Array
(
[0] => Current City
)
)
[2] => Array
(
[parent] => Known me
[parentId] => 5
[child] => Array
(
[0] => My personality
[1] => Best life moment
)
)
)
For that I coded :
$filter = array();
$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 results :
Array
(
[0] => Array
(
[parent] => Basic
[parentId] => 1
[child] => Array
(
[0] => Birthday
)
)
[1] => Array
(
[parent] => Geo
[parentId] => 10
[child] => Array
(
[0] => Current City
)
)
[2] => Array
(
[parent] => Known me
[parentId] => 5
[child] => Array
(
[0] => My personality
)
)
)
Could anyone point out my missing LOC?