Home > Net >  Multidimensional array to string conversion with custom format
Multidimensional array to string conversion with custom format

Time:02-15

Dear,

I have a multidimensional array and I need to write the information contained therein in a text file, but in a customized way because I have another program to read this information and I cannot use another method.

First, my array:

Array ( 
    [0] => Array ( 
        [Name] => test1 
        [Address] => 192.168.1.103 
        [Port] => 8080 
        [Password] => '654321' 
        ) 
    [1] => Array ( 
        [Name] => test2 
        [Address] => 192.168.1.104 
        [Port] => 8080 
        [Password] => '654321' 
        ) 
    [2] => Array ( 
        [Name] => test3 
        [Address] => 192.168.1.105 
        [Port] => 8080 
        [Password] => '654321' 
        ) 
)

The Format I need it to have:

Host {
Name = test1
Address = 192.168.1.103
Port = 8080
Password = '654321'
}
Host {
Name = test2
Address = 192.168.1.104
Port = 8080
Password = '654321'
}
Host {
Name = test3
Address = 192.168.1.105
Port = 8080
Password = '654321'
}

My code:

function ArrayToString($array){
       $i = 0;
       foreach($array as $chaveclient){
                                    
       $chaveclient = $array[$i];
                                    
       $format = "Host {\n 
         Name = %s\n
         Address = %s\n
         Port = %s\n
         Password = %s\n";
                                
        $string = sprintf($format, 
          $chaveclient["Name"], 
          $chaveclient["Address"],
          $chaveclient["Port"],
          $chaveclient["Password"];
    
         $i  ;
     }
                                  
return $string;
                                
}
    
echo ArrayToString($array);

But this code only brings me 1 Host from the array. How do I bring all hosts?

CodePudding user response:

$array = [
  [ 'Name' => 'test1', 'Address' => '192.168.1.103', 'Port' => 8080, 'Password' => '654321' ],
  [ 'Name' => 'test2', 'Address' => '192.168.1.104', 'Port' => 8080, 'Password' => '654321' ],
  [ 'Name' => 'test3', 'Address' => '192.168.1.105', 'Port' => 8080, 'Password' => '654321' ]
];

function ArrayToString($array) {
  $string = '';
  foreach ($array as $item) {
    $format = "Host {\nName = %s\nAddress = %s\nPort = %s\nPassword = '%s'\n}\n";
    $string .= sprintf($format, $item['Name'], $item['Address'], $item['Port'], $item['Password']);
  }
  return $string;
}

echo ArrayToString($array);

Alternative using array_map:

$result = implode(
    "\n",
    array_map(
        fn($v) => "Host {\nName = {$v['Name']}\nAddress = {$v['Address']}\nPort = {$v['Port']}\nPassword = '{$v['Password']}'\n}",
        $array
    )
);
  • Related