1

I have the following function:

public static function toArray($key, $value) {

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

    $return = array();

    for($i = count($e) - 1; $i >=  0; $i--) {

        $return = array($e[$i] => $return);

    }

    return $return;

}

and the output:

Array
(
    [app] => Array
        (
            [shifts] => Array
                (
                    [total] => Array
                        (
                        )

                )

        )

)

And desired output:

Array
(
    [app] => Array
        (
            [shifts] => Array
                (
                    [total] => 3
                )

        )

)

What happens here is that a string is given and and creates a multi-dimensional array using the dot as the delimiter. However, I wish to assign the last array a value given by the function. This example is assuming that the string input is: "apps.shifts.total" with a value of 3. I'm trying to find an elegant way to achieve this without going into useless loops. Any inspiration would be much appreciated!

1 Answer 1

1

You're initialization step is wrong.

Try:

public static function toArray($key, $value) {
    $e = explode('.', $key);
    $return = $value; // MODIFIED HERE
    for($i = count($e) - 1; $i >=  0; $i--) {
        $return = array($e[$i] => $return);
    }
    return $return;
}

What you basically do is cascade to the top. But you start with an empty array. Instead, you can simply start with the value and cascade the array around it.

Example (using interactive php -a):

$ php -a
Interactive mode enabled

php > function toArray($key, $value) {
php {     $e = explode('.', $key);
php {     $return = $value; // MODIFIED HERE
php {     for($i = count($e) - 1; $i >=  0; $i--) {
php {         $return = array($e[$i] => $return);
php {     }
php {     return $return;
php { }
php > var_dump(toArray('apps.shifts.total',3));
array(1) {
  ["apps"]=>
  array(1) {
    ["shifts"]=>
    array(1) {
      ["total"]=>
      int(3)
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Funny enough is that I had just realized what my mistake was and needed to assign the value instead of initializing an array. Thanks for reinforcing!

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.