[英]How to get PHP value from input using Tagify
I have a problem with submitting a PHP form using jQuery Tagify .我在使用jQuery Tagify提交 PHP 表单时遇到问题。
If I add 2 tags like John
and Thomas
, then I'm getting $_POST['tag']
as:如果我添加 2 个标签,例如
John
和Thomas
,那么我得到$_POST['tag']
为:
'[{"value":"John"}, {"value":"Thomas"}]'
How I can change my $_POST['tag']
to get this POST as: John,Thomas
?我如何更改我的
$_POST['tag']
以获得此 POST: John,Thomas
?
var_dump(implode(', ', array_column(json_decode($_POST['tag']), 'value')));
First you decode the JSON coming in $_POST['tag']
into an array/object structure. 首先,您将
$_POST['tag']
传入的JSON解码为数组/对象结构。 array_column
gives you the flat array with the values. array_column
为您提供带有值的平面数组。 Then you join it separated by commas ( implode
). 然后,将其加入并以逗号分隔(
implode
)。
Yes, the square brackets is in the way.是的,方括号挡住了。 In fact, tagify-js outputs an array of json objects.
事实上,tagify-js 输出了一个包含 json 个对象的数组。 So json_decode function doesn't work either.
所以 json_decode function 也不起作用。 It is necessary to prepare the output.
需要准备output。
Here is the function I implemented to save the input value.这是我为保存输入值而实现的 function。 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'] );
用法:
br_bookmarks_tagify_json_to_array( $_POST['tag'] );
Hope it helps others.希望它能帮助别人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.