-1

I have a function for arrays that I insert in db.

$data = array(
 "This\tIs\tAn\tExample\tOne\tOf\tMy\tArrays\"
);

I formatted it correctly and given output is with:

$result = array_walk($data, function(&$item) { $item = '{ ' .str_replace("\t", ', ', $item) . ' }'; });

and the result of one of the rows that is inserted in db in JSON format is:

{ This, is, Example }, {  One, Of, My, Arrays}

and all of them are formatted that way.

How can I bypass this to get desired format like:

{ This, is, Example, One, Of, My, Arrays}
Elementor
  • 57
  • 7
  • That is not valid JSON to begin with - curly braces mean object, so you would need to have key-value pairs in there. – 04FS Nov 07 '19 at 14:21
  • 3
    *I formatted it correctly*, I disagree. Why are you not using `explode` on the string, then simple `json_encode`? – Lawrence Cherone Nov 07 '19 at 14:23
  • as your code should work, if you remove the last \ in $data, and why should there be a quote afer One ? it would be helpfull to see the execution of the query in php – FatFreddy Nov 07 '19 at 14:23
  • When I run the given code,`$data` is an array and contains `{ This, Is, An, Example, One, Of, My, Arrays }` as the first element. So it looks strange that your dumped output looks different - especially as `An` has vanished both in the current and the expected output – Nico Haase Nov 07 '19 at 14:37

1 Answers1

-1

If you want to convert this

$data = array(
 "This\tIs\tAn\tExample\tOne\tOf\tMy\tArrays\"
);

to this

{ This, is, Example, One, Of, My, Arrays}

you can simply do it by

$result = [];
    foreach ($data as $index => $value) {
        $result[] = implode(',', explode("\t", $value));
    }
    $result = '{' . implode(',', $result) . '}';
George Dryser
  • 322
  • 1
  • 7
  • 1
    It returns ""{Id,FirstName,LastName,DateOfBirth,Phone,Address1,Address2,City,State,PostCode,Country,Email}"" with minor correction of explode('\\', $value)) to explode("\t", $value)) @GeorgeDryser – Elementor Nov 07 '19 at 14:47
  • You will also need to change it to use double quotes `"\t"` – Nigel Ren Nov 07 '19 at 15:04