PHP - modify formatted array

76 Views Asked by At

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}
1

There are 1 best solutions below

2
George Dryser On

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) . '}';