我在使用jQuery Tagify提交PHP表单时遇到了一个问题。
如果我添加像John和Thomas这样的两个标签,那么我得到的$_POST['tag']是:
'[{"value":"John"}, {"value":"Thomas"}]'如何更改我的$_POST['tag']以获取此帖子:John,Thomas
发布于 2019-02-25 02:14:13
var_dump(implode(', ', array_column(json_decode($_POST['tag']), 'value')));首先,将$_POST['tag']中的JSON解码为数组/对象结构。array_column为您提供了带有值的平面数组。然后用逗号(implode)将其连接起来。
发布于 2022-02-22 14:42:16
是的,方括号挡道了。实际上,tagify-js输出一个json对象数组。所以json_decode函数也不起作用。有必要准备输出。
下面是我实现的保存输入值的函数。它将它们转换为值的数组。
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;
}
}用法:br_bookmarks_tagify_json_to_array( $_POST['tag'] );
希望它能帮助其他人。
https://stackoverflow.com/questions/54854892
复制相似问题