Given the following array:
array(
0 => array(
0 => 56,
1 => array(
0 => 57,
1 => 58,
2 => 59,
),
2 => 60
),
1 => array(
0 => 61,
1 => array(
0 => 62,
1 => array(
0 => 63,
1 => 64
)
)
)
)
How could I proceed to remove elements from that array starting from deepest elements? My elements are ID in a database and key constraints make me unable to delete parents if they have children...
I looked for something using RecursiveIterator but no solution so far...
Actually, no need to get a specific algo, a standard recursion will do the job
You can visit leaves only with RecursiveIteratorIterator and RecursiveIteratorIterator::LEAVES_ONLY mode and then reverse the resulting array:
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($ids),
RecursiveIteratorIterator::LEAVES_ONLY
);
$ids = [];
foreach ($iterator as $id) {
// You can put elements directly in the beggining of an array
// or reverse array later.
// array_unshift($ids, $id);
$ids[] = $id;
}
$ids = array_reverse($ids);
Here is working demo.