0

I`ve got an associative array which looks like the following:

[
'one' => [
    'two' => [
        'three1' => 1,
        'three2' => 'somestring',
    ]
] some more nodes...

I need to reverse it to the following:

'one.two.three1'=>1,
'one.two.three2'=>'somestring',
etc...

I can build the first string but for the second one it outputs only:

'three2'=>somestring'

but I need it to iterate from the beginning of the node. My code looks like the following:

$arr2 = array();
$finalarray = array();

function rewrapback($arr, &$arr2, &$finalarray, $level=0)
{
    foreach($arr as $k=>$v)
    {
        $startnode = $k;
        if(is_array($v))
        {  
            $level=$level+1; //I suppose I need to do something with this but I don`t know what
            array_push($arr2, $k);
            rewrapback($v, $arr2, $finalarray,$level);
        }else
        {
            array_push($arr2, $k);
            $string = implode(',', $arr2);
            $finalarray[$string]=$v;
            $arr2 = array();   //reset the string
        }
    }
    return $finalarray;
}

Any ideas on how to fix that? Thank you

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Jack
  • 857
  • 14
  • 39
  • 1
    http://php.net/reset but note that this'll probably throw off ALL of the foreach loops, since the pointer is associated with the array, NOT the loop using it. – Marc B Aug 23 '16 at 20:02
  • since the question has been closed, you can something similar to this: `function rewrapback($list, $keyIndex = '') { foreach ($list as $key=>$value) { if (is_array($value)) { $keyIndex .= ".$key"; rewrapback($value, $keyIndex); continue; } echo "$keyIndex.$key = $value \n"; } }` – Kamrul Khan Aug 23 '16 at 20:47

0 Answers0