'How to get PHP value from input using Tagify

I have a problem with submitting a PHP form using jQuery Tagify.

If I add 2 tags like John and Thomas, then I'm getting $_POST['tag'] as:

'[{"value":"John"}, {"value":"Thomas"}]'

How I can change my $_POST['tag'] to get this POST as: John,Thomas?

php


Solution 1:[1]

var_dump(implode(', ', array_column(json_decode($_POST['tag']), 'value')));

First you decode the JSON coming in $_POST['tag'] into an array/object structure. array_column gives you the flat array with the values. Then you join it separated by commas (implode).

Solution 2:[2]

Yes, the square brackets is in the way. In fact, tagify-js outputs an array of json objects. So json_decode function doesn't work either. It is necessary to prepare the output.

Here is the function I implemented to save the input value. It converts them to an array of values.

function br_bookmarks_tagify_json_to_array( $value ) {

    // Because the $value is an array of json objects
    // we need this helper function.

    // First check if is not empty
    if( empty( $value ) ) {
        
        return $output = array();

    } else {

        // Remove squarebrackets
        $value = str_replace( array('[',']') , '' , $value );

        // Fix escaped double quotes
        $value = str_replace( '\"', "\"" , $value );

        // Create an array of json objects
        $value = explode(',', $value);

        // Let's transform into an array of inputed values
        // Create an array
        $value_array = array();

        // Check if is array and not empty
        if ( is_array($value) && 0 !== count($value) ) {

            foreach ($value as $value_inner) {
                $value_array[] = json_decode( $value_inner );
            }

            // Convert object to array
            // Note: function (array) not working.
            // This is the trick: create a json of the values
            // and then transform back to an array
            $value_array = json_decode(json_encode($value_array), true);

            // Create an array only with the values of the child array
            $output = array();

            foreach($value_array as $value_array_inner) {
                foreach ($value_array_inner as $key=>$val) {
                    $output[] = $val;
                }
            }

        }

        return $output;

    }

}

Usage: br_bookmarks_tagify_json_to_array( $_POST['tag'] );

Hope it helps others.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quasimodo's clone
Solution 2 Luiz Lopes