Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string to form multidimensional array keys? [duplicate]

Tags:

arrays

php

I'm creating JSON encoded data from PHP arrays that can be two or three levels deep, that look something like this:

[grandParent] => Array (
                       [parent] => Array (
                                         [child] => myValue 
                                      )
                    )

The method I have, which is simply to create the nested array manually in the code requires me to use my 'setOption' function (which handles the encoding later) by typing out some horrible nested arrays, however:

$option = setOption("grandParent",array("parent"=>array("child"=>"myValue")));

I wanted to be able to get the same result by using similar notation to javascript in this instance, because I'm going to be setting many options in many pages and the above just isn't very readable, especially when the nested arrays contain multiple keys - whereas being able to do this would make much more sense:

$option = setOption("grandParent.parent.child","myValue");

Can anyone suggest a way to be able to create the multidimensional array by splitting the string on the '.' so that I can json_encode() it into a nested object?

(the setOption function purpose is to collect all of the options together into one large, nested PHP array before encoding them all in one go later, so that's where the solution would go)

EDIT: I realise I could do this in the code:

$options['grandparent']['parent']['child'] = "myValue1";
$options['grandparent']['parent']['child2'] = "myValue2";
$options['grandparent']['parent']['child3'] = "myValue3";

Which may be simpler; but a suggestion would still rock (as i'm using it as part of a wider object, so its $obj->setOption(key,value);

like image 479
Codecraft Avatar asked Feb 20 '26 00:02

Codecraft


1 Answers

This ought to populate the sub-arrays for you if they haven't already been created and set keys accordingly (codepad here):

function set_opt(&$array_ptr, $key, $value) {

  $keys = explode('.', $key);

  // extract the last key
  $last_key = array_pop($keys);

  // walk/build the array to the specified key
  while ($arr_key = array_shift($keys)) {
    if (!array_key_exists($arr_key, $array_ptr)) {
      $array_ptr[$arr_key] = array();
    }
    $array_ptr = &$array_ptr[$arr_key];
  }

  // set the final key
  $array_ptr[$last_key] = $value;
}

Call it like so:

$opt_array = array();
$key = 'grandParent.parent.child';

set_opt($opt_array, $key, 'foobar');

print_r($opt_array);

In keeping with your edits, you'll probably want to adapt this to use an array within your class...but hopefully this provides a place to start!

like image 91
rjz Avatar answered Feb 21 '26 13:02

rjz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!