1

i have text separated by newline

/EXT/123/SOMEPARAM:VALUE123
/EXT/123/other:VALUE222

i created some code for create array with childrens.

array_merge_recursive make incorrect array if keys is numeric, i add @ symbol and result is correct

$astdb_array=explode("\n", $astdb_raw);

$db_data = []; $result=[];
foreach($astdb_array as $db_row){

  $db_row = trim(preg_replace('/\s/', '', $db_row));
  $row_elements = explode('/', $db_row);

   if(sizeof($row_elements)>0){
       $key = array_shift($row_elements);
       #$db_data= create_array($row_elements);
       foreach(array_reverse($row_elements) as $child){

             if (strpos($child, ':') !== false) {
                [$kkey, $vval] = explode(':',$child);
                $key = [$kkey => $key = $vval];
            }else{
                    if(is_numeric($child)){
                          $key = [ '@'.$child => $key];
                    }else{
                          $key = [$child => $key];
                    }
             }
       }
 $db_data[]=$key;
   }
}
$array_result = call_user_func_array('array_merge_recursive',$db_data);
print json_encode($array_result);

function result

Array
(
    [EXT] => Array
        (
            [@104] => Array
                (
                    [MOBILE] => 77761587000
                    [TENANT] => customer1
                    [TRUNK] => customer1
                    [TRUNKID] => 2
                )

            [@110] => Array
                (
                    [MOBILE] => 77761587000
                    [TENANT] => customer1
                    [TENANTID] => 2
                    [TRUNK] => customer1
                    [TRUNKID] => 2
                )

        )

    [ROUTES] => Array
        (
            [@1] => Array
                (
                    [PATTERN] => 5555
                    [PERMS] => type,any,end
                )

            [@2] => Array
                (
                    [NAME] => KZ
                    [PATTERN] => _XXXXXXXXXXX
                    [PERMS] => type,any,end
                    [TYPE] => OUTDOOR
                )

        )

)

Result is correct, but need remove symbol @ from keys, tried with:

$result = array_map(function($s){return str_replace('@','',$s);}, $array_result);

and this not helps me. Please help solve this problem.... thx.

Solved

My Solution:

 array_map(function(&$a){
     $kv=[];
     array_walk($a,function($v,&$k) use (&$kv) { $k=str_replace('@','',$k);   $kv[$k] = $v; }   );
     return $kv;
}, $array_result);
Dmitry
  • 33
  • 5

0 Answers0