1

I want to write a function that modifies an array like this:

function addDataToArray($array,array("data","userdata","username"),"john") { // do something here }

result will be $array["data"]["userdata"]["username"]="john"

I'm aware that it would be much easier to achieve this in normal ways but I need to learn if this can be done. Thanks

2
  • What have you already tried? I'm not writing your function for you. Commented Mar 3, 2015 at 16:36
  • I guess that the thing that you need is the reference notion : php.net/manual/en/language.references.pass.php. If not, please answer Zarathuztra's question, and we'll try to help you. Commented Mar 3, 2015 at 16:42

2 Answers 2

1

This code should works for you. I was a little bit inspired by this question:

function addDataToArray(&$array,$input_array,$string) { 

    $count = count($input_array)-1;
    $tmp = array($input_array[$count]=>$string);

    for ($i=$count-1;$i>=0;$i--) {
        $arr = array();
        $arr[$input_array[$i]] = $tmp;
        $tmp = $arr;
    }

    $array = array_merge($array, $arr);
}

$array = array(); //or your inicialized $array
addDataToArray($array,array("data","userdata","username"),"john");

var_dump($array);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I got the idea behind it.
1

With recursion

$array = array("foo" => "bar"); 

function addDataToArray(&$a, $path, $val) 
{ 
    if (count($path) == 1) { 
        $path = $path[0]; 
    } 
    if (!is_array($path)) { 
        $a[$path] = $val; 
        return $a; 
    } 
    $b = array(); 
    $a[array_shift($path)] = addDataToArray($b, $path, $val); 
    return $a; 
} 
addDataToArray($array, array("data","userdata","username"),"john"); 
var_dump($array); 

Result

array(2) {
  ["foo"]=>
  string(3) "bar"
  ["data"]=>
  array(1) {
    ["userdata"]=>
    array(1) {
      ["username"]=>
      string(4) "john"
    }
  }
}

1 Comment

Sorry, but your code doesn't work - it is not generating multidimensional array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.