Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – how to convert array of values to array with nested keys from values of first array?

I have this array:

$input = ['a', 'b', 'c', 'd'];

the output should be:

$output = convertArrayValues($input, 'final');

$output['a']['b']['c']['d'] = 'final;

I need code for convertArrayValues() method which will do the job of converting:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$input = ['a', 'b', 'c', 'd'];

into:

 $output['a']['b']['c']['d'] = 'final;

Dumped array input:

array:4 [
  0 => "a"
  1 => "b"
  2 => "c"
  3 => "d"
]

Dumped array output:

array:1 [
  "a" => array:1 [
    "b" => array:1 [
      "c" => array:1 [
        "d" => 'final
      ]
    ]
  ]
]

>Solution :

Will this help?

function convertArrayValues($input, $value) {
    $output = [];
    $temp = &$output; // reference to the output array 

    foreach ($input as $key) {
        $temp[$key] = []; // create or set a nested array if it's the last item
        $temp = &$temp[$key]; // update reference to point to the newly created array
    }

    $temp = $value; // final value

    return $output;
}
convertArrayValues($input, 'final');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading