I have an array $heap = array(9, 9, 9, 8, 9, 9, 8, 9, 9, 9, 9, 9, 8, 8, 9, 7, 9, 8, 8, 9, 9,);
and I want to output It like binary tree, when the two children nodes we can know by this formulas, $heap[$key*2+1]
and second $heap[$key*2+2]
. I try to run using foreach but getting error about undefined offset 21. Here is foreach:
foreach ($heap as $key => $value) {
echo $value;
if ($key != count($heap)) {
echo $heap[$key*2+1];
echo $heap[$key*2+2];
}
}
What I am doing wrong and how I can solve this?