0

I'm try to code a solution for convert a multidimensional array (more 2 nested) on PHP 5.6+

Try with RecursiveIteratorIterator, but i don't understand well, and not work.

array:3 [
  "app" => array:3 [
    "cp" => array:3 [
      "production" => true
      "panel" => "cpanel"
      "home" => "/home"
    ]
    "rsync" => array:4 [
      "binary" => "/usr/bin/rsync"
      "options" => " -azhv --inplace --delete"
      "options_extra" => " -azvh --checksum --no-times --no-o --no-g --inplace --delete"
      "local" => "/cprsync_back"
    ]
    "remotes" => array:1 [
      "master" => array:4 [
        "ip" => "1.1.1.1"
        "user" => "myuser"
        "port" => "myport"
        "path" => "/Volumes/MACBACKUP/cprsync_remote/hq"
      ]
    ]
  ]
  "app" => array:5 [
    "name" => "CpRsync"
    "log_level" => "debug"
    "timezone" => "Europe/Madrid"
    "locale" => "en"
    "fallback_locale" => "en"
  ]
  "mail" => array:6 [
    "driver" => "smtp"
    "host" => "smtp.host.com"
    "port" => "26"
    "encryption" => "tls"
    "username" => "userpop@host.com"
    "password" => "z4t3@#w2Qwa8OM"
  ]
]

This I like it:

array:22 [
   "app.cp.producction" => true
   "app.cp.panel" => "cpanel"
   ...
   "remotes.master.ip" => "1.1.1.1"
   "remotes.master.user" => "myuser" 
   ...
]

The best way for me it's

private function  flattenArrayDot($array, $prepend = '')
    {
        $results = [];

        foreach ($array as $key => $value) {
            if (is_array($value) && ! empty($value)) {
                $results = array_merge($results, $this->flattenArrayDot($value, $prepend.$key.'.'));
            } else {
                $results[$prepend.$key] = $value;
            }
        }

        return $results;
    }

Code work, but, it's a correct way? Best paint code it's possible?

abkrim
  • 3,512
  • 7
  • 43
  • 69
  • Why would you want to do this? It adds a lot of repetitive information. You are essentially adding code to the data. – zaph Oct 22 '16 at 11:22
  • ooh.. thanks. I don't see on my search. Even the title is almost identical. The search engine or google gave me is post, with many possible solutions. Thank you. @trincot – abkrim Oct 22 '16 at 15:32

0 Answers0