[英]How to get PHP value from input using Tagify
我在使用jQuery Tagify提交 PHP 表單時遇到問題。
如果我添加 2 個標簽,例如John
和Thomas
,那么我得到$_POST['tag']
為:
'[{"value":"John"}, {"value":"Thomas"}]'
我如何更改我的$_POST['tag']
以獲得此 POST: John,Thomas
?
var_dump(implode(', ', array_column(json_decode($_POST['tag']), 'value')));
首先,您將$_POST['tag']
傳入的JSON解碼為數組/對象結構。 array_column
為您提供帶有值的平面數組。 然后,將其加入並以逗號分隔( implode
)。
是的,方括號擋住了。 事實上,tagify-js 輸出了一個包含 json 個對象的數組。 所以 json_decode function 也不起作用。 需要准備output。
這是我為保存輸入值而實現的 function。 它將它們轉換為值數組。
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'] );
希望它能幫助別人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.