0

I have a multiple level array field need to be submit via a form. Not sure what will be the easiest solution:

As php will auto convert dot to underscore, so i change it to array:

$form['a.b_b.c'] ==> <input name="a[b_b][c]" value="$form[a.b_b.c]">

And I got $_POST[a][b_b][c] correctly.

But what is the easiest way to assign this $_POST value back to the original $form['a.b_b.c'] without much loops? eg

$form['a.b_b.c'] = $_POST['a']['b_b']['c'];

Or is there a better way to walk around?

very close to this question but still not yet: Convert dot syntax like "this.that.other" to multi-dimensional array in PHP

And here is my current solution:

foreach ($form as $k) {
    $form[$k] = assign_val($_POST, $k);
}

function assign_val($arr = [], $key = '') {
    $keys = explode('.', $key);
    $val = &$arr;
    foreach ($keys as $k) {
        $val = &$val[$k];
    }
    return $val;
}
Community
  • 1
  • 1
SIDU
  • 2,258
  • 1
  • 12
  • 23
  • 1
    Not 100% what you want, but maybe extract() will help you? http://php.net/manual/en/function.extract.php – Drew Baker Feb 07 '17 at 23:37
  • perhaps you could show us the form and explain the issue a little better –  Feb 07 '17 at 23:55
  • I would like to recommend changing the title to *"How to convert ['a'=>['b'=>['c'=>'d']]] to ['a.b.c'=>'d'] easily"* – Cave Johnson Feb 08 '17 at 00:33

1 Answers1

1

I would have a function flatten and do something like:

function flatten($array, $prefix = '') {
    $result = array();
    foreach($array as $key=>$value) {
        if(is_array($value)) {
            $result = $result + flatten($value, $prefix . $key . '.');
        }
        else {
            $result[$prefix . $key] = $value;
        }
    }
    return $result;
}

And then you can do:

$form = flatten($_POST);
dave
  • 62,300
  • 5
  • 72
  • 93
  • I do not want all _POST, only need keys exists in $form – SIDU Feb 08 '17 at 00:30
  • @SIDU You could just call `array_intersect_key` to get only the values that have keys that exist in both arrays and then use `array_merge` to merge in those values. Like this: `array_merge($form, array_intersect_key(flatten($_POST), $form));` – Cave Johnson Feb 23 '17 at 01:43