多维数组到具有自定义格式的字符串转换

Multidimensional array to string conversion with custom format

亲爱的,

我有一个多维数组,我需要将其中包含的信息写入一个文本文件,但是以自定义的方式,因为我有另一个程序来读取这些信息,我不能使用其他方法。

首先,我的数组:

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' 
        ) 
)

我需要的格式:

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'
}

我的代码:

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);

但是这段代码只给我带来了数组中的 1 个主机。如何带上所有主机?

$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);

替代使用array_map:

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