php – materializecss | explode JSON string form Chips into array to INSERT to mysql-ThrowExceptions

Exception or error:

I have the following code to send chipsData from chips to an input form.

        onChipAdd: (event, chip, modal) => {
             var chipsData = M.Chips.getInstance($('.chips')).chipsData;
             var chipsDataJson = JSON.stringify(chipsData);
             $('#ModalEdit #userEventData').val(chipsDataJson);
         },
         onChipSelect: () => {

         },
         onChipDelete: () => {
             var chipsData = M.Chips.getInstance($('.chips')).chipsData;
             var chipsDataJson = JSON.stringify(chipsData);
             $("#userEventData").val(chipsDataJson);
         }
  }

The form input field:

<input type="hidden" name="userEventData" id="userEventData" value="">

When I echo it I receive a string as follow: [{"tag":"name1"},{"tag":"name2"}]

I am looking for a solution to transfer it from a string to an array for later insert it to a database.
Any ideas?

*I already checked other Question and could find any solution.
(How to store and retrieve materializecss chips?)

How to solve:

What you are getting is so called JSON encoded data. You can decode it in PHP using the json_decode() function, which will (in your case) give you a two-dimensional array to work with:

$json = '[{"tag":"name1"},{"tag":"name2"}]'
var_export(json_decode($json, true));

output:

array (
  0 => 
  array (
    'tag' => 'name1',
  ),
  1 => 
  array (
    'tag' => 'name2',
  ),
)

Note that I passed true as the second parameter to json_decode() since I like to work with arrays rather than objects.

Leave a Reply

Your email address will not be published. Required fields are marked *