user5405648
user5405648

Reputation:

PHP: Dynamically copying the contents of an array?

I have two arrays, and a function.

private $configuration;
private $parameters;

private function setParameters() {
    // 
}

Inside the setParameters function, I want to assign elements to the parameters array. Both of these variables are arrays, and I need to copy the contents from configuration to parameters.

Configuration array works a little different, inside the configuration are nested arrays, the array configuration merely contains file names, inside that are nested arrays, similar to Laravel's config.

So, here is an example of how my configuration structure may look, sorry if you notice any mistakes, I hand wrote this without a text editor or IDE.

These arrays may go much further in terms of nesting, I just kept it simple here for readability.

[   
    "config_file_1" => [
        [
            "name" => "Example",
            "author" => "John"
        ]
    ],

    "config_file_2" => [
        [
            "country" => "Japan",
            "city" => "Tokyo"
        ]
    ],
]

This would need to be the equifalent to the code below.

$this->parameters["config_file_1.name"] = "Example";
$this->parameters["config_file_1.author"] = "John";
$this->parameters["config_file_2.country"] = "Japan"; // ETC, ETC...

Upvotes: -1

Views: 50

Answers (1)

TsV
TsV

Reputation: 639

              $configuration = [
        'config_file_1'=> [
            "name" => "Example",
            "author" => ['John', 'Do', 'Ou']],
        'config_file_2' => [
            "country" => "Japan",
            "city" => ["1", '2', '3'],
            'val' => ['a'=>'x', 'b'=> 'y']]
    ];

        $parameters = [];

    foreach($configuration  as $con => $config){
        foreach($config as $key => $value){
            if(is_array($value)){
                foreach($value as $keys => $value){
                    $parameters["{$con}.{$key}.{$keys}"] = $value;
            }} else {
                $parameters["{$con}.{$key}"] = $value;
            }
        }
    }

        print_r($parameters);
//        Array
//        (
//            [config_file_1_name] => Example
//            [config_file_1_author] => John
//            [config_file_2_country] => Japan
//            [config_file_2_city] => Tokyo
//        )

Upvotes: 1

Related Questions