2

How do I convert an input name array to dot notation, similar to the way the validator handles keys? I'd like it to work for non-arrays as well.

For example, say I have:

$input_name_1 = 'city';
$input_name_2 = 'locations[address][distance]';

How would I convert that to:

$input_dot_1 = 'city';
$input_dot_2 = 'locations.address.distance';
redbastie
  • 159
  • 7
  • 2
    What have you tried? Stackoverflow is not a code-writing service; you're expected to make an effort to solve your own issue, and we'll assist with debugging. – Tim Lewis May 14 '20 at 19:35
  • Laravel have method for it. Its called array_get() and inverse method array_set(). Mode here: https://stackoverflow.com/a/39118759/4771277 – Autista_z May 14 '20 at 19:36
  • Not sure why all the hate on this question. It cropped up for me yesterday and unfortunately there are no helpful answers on this post yet. I have added the solution I came to as an answer. – benjaminhull Jun 02 '21 at 07:55

2 Answers2

0

If we're just talking about converting the string representation, e.g. converting strings as follows...

  • foo[1] -> foo.1
  • foo[bar] -> foo.bar
  • foo[bar][baz] -> foo.bar.baz

The following code does it just fine...

$string = str_replace('[', '.', $string); // Replace [ with .
$string = str_replace(']', '', $string); // Remove ]

NOTE: I could not find anyway to achieve this within the Laravel framework using existing Laravel classes/methods - but would love to know if there is a way.

benjaminhull
  • 525
  • 3
  • 11
-1

Here is a hint, you could remove ] and then replace [ with a dot:

psuedocode:

$input_name_2 = 'locations[address][distance]';
$halfway = removeClosingBracket($input_name_2); // locations[address[distance
$result = replaceOpeningBracektWithDot($halfway); // locations.address.distance
Joel Harkes
  • 10,036
  • 3
  • 45
  • 62