2

Possible Duplicate:
String with array structure to Array

I have a string "db/yum/user", and I'm trying to explode it so each element of / becomes a deeper dimension.

So the direct method of creating the data variable would be

$config['db']['yum']['user'] = "val";

My attempt so far:

$config = array();              
  function set_config($key,$value){
global $config;

        //Multi deminsional config
        $multi_configs = explode('/',$key);
        if($multi_configs!==false){
            $build_up = array();
            $c =& $build_up;

            foreach($multi_configs as $multi_config){
                $c[$multi_config] = array();
                $c     =& $c[$multi_config];
            }
            //$c = $value;
            array_merge($config,$c);
            return;
        }


        $config[$key] = $value;
    }
               set_config('db/yum/user','val');
               set_config('db/yum/server','val2');
                //etc,etc,etc, this was modified to make more sense in this context.
Community
  • 1
  • 1
Mattisdada
  • 979
  • 1
  • 15
  • 24
  • Infinitely? Do you have a quantum server to handle that? – Fabrício Matté Nov 09 '12 at 13:35
  • @FabrícioMatté The trick is to get the scripts execution that slow with growing index that you can add hardware faster than the script adds elements :-) – arkascha Nov 09 '12 at 13:49
  • I have an alternative answer which should fully answer the question of having a reusable function for setting several values within the same "config" variable through successive function calls. My recommendation is to use some recursion. It should handle all that you need and I hope it helps. [RecursiveFunsies](http://ideone.com/jJ8bvl) – EmmanuelG Nov 09 '12 at 17:18

2 Answers2

10

This is probably what you are looking for:

#!/usr/bin/php
<?php

$config = array();

function set_config($key, $value) {
  global $config;

  if (FALSE=== ($levels=explode('/',$key)))
    return;

  $pointer = &$config;
  for ($i=0; $i<sizeof($levels); $i++) {
    if (!isset($pointer[$levels[$i]]))
      $pointer[$levels[$i]]=array();
    $pointer=&$pointer[$levels[$i]];
  } // for

  $pointer=$value;
} // set_config

set_config('db/yum/user','val');
set_config('db/yum/server','val2');

print_r($config);

?>

The output is:

Array
(
    [db] => Array
        (
            [yum] => Array
                (
                    [user] => val
                    [server] => val2
                )

        )

)
arkascha
  • 41,620
  • 7
  • 58
  • 90
  • You can also use foreach loop , which will make this code bit cleaner :) – MD. Sahib Bin Mahboob Nov 09 '12 at 14:30
  • I get `Cannot create references to/from string offsets nor overloaded objects` on the line where you have `$pointer=&$pointer[$levels[$i]];` – JPMC Aug 05 '15 at 17:45
  • @JPMC Just checked again, the code still works for me as expected. Either you have a different environment (php version and so on), or you have different values. – arkascha Aug 05 '15 at 17:48
  • @arkascha My PHP version is 5.4.19, what about yours? – JPMC Aug 05 '15 at 17:52
  • @JPMC Should work with that. You run _exactly_ the same code? Even for a test? Then what else is different? Operating system, running php not on CLI but inside an http server? – arkascha Aug 05 '15 at 17:53
  • @arkascha It would seem there was mistake in my copying of this code, I was using this to set multiple nested values in a loop, and when a value was previously set to a string, it was later trying to extend off of that like an array. Apologies for the mix-up, and thanks for the solution! Even with my confusion, this still saved me time. – JPMC Aug 05 '15 at 18:26
  • 1
    I really like this code. It taught me a lot about pointers too. Thanks. – Chud37 Apr 30 '18 at 13:36
  • This is a gorgeous piece of code! – Sean Kendle Jun 26 '19 at 13:01
2

You can also achieve the same solution using a tree structure in the array . Here is the code to construct the array :

$arr = array (5,6);

$new_arr=array ();
$prev=0;

foreach ($arr as $val) {
    $new_arr[$prev] = $val;
    $prev=$val;
}

$new_arr[$prev]="value";

Here is the code to retrieve the value:

    function retrieve ($arr) {

    $prev=0;
    while (1) {
        if (! isset($arr[$prev] ) )
            break;
        else $prev = $arr[$prev];

    }       
    return $prev;       
}
MD. Sahib Bin Mahboob
  • 20,246
  • 2
  • 23
  • 45