在我的應用程式中,我需要將 JavaScript 物件轉換為作為文本字串回傳的原始 PHP 陣列。我會通過呼叫 API 來做到這一點。我不需要操縱陣列。在我的 JavaScript 應用程式中,我只需要如下所示的普通 PHP 物件字串。(就像使用這個:https ://wtools.io/convert-js-object-to-php-array )
JavaScript 物件是:
{
"name":"A Name",
"_typography": {
"color": {
"hex":"#2196f3"
},
"text-transform":"uppercase",
"font-weight":"600"
}
}
我如何將 JavaScript 物件發送到 PHP 函式
JSON.stringify(jsObject);
我需要什么作為字串輸出:
[
"name" => "A Name",
"_typography" => [
"color" => [
"hex" => "#2196f3"
],
"text-transform" => "uppercase",
"font-weight" =>"600"
]
]
我嘗試的是首先json_decode將 JavaScript 物件轉換為 PHP 物件,然后嘗試將其作為純字串回傳。但沒有機會。我要么得到一個 Js 物件,要么完全得到其他東西。我沒有更多的想法了。
我的嘗試
function convert_js_object_to_php(WP_REST_Request $request) {
// Getting the JS object
$object = $request->get_header('js_object');
// Decoding it to a PHP object
$output = json_decode($object);
if ($output) {
return strval($output);
// return $output (Here I also get the JavaScript object again)
// return implode($output) (I don't get the plain PHP array)
}
return false;
}
你有什么主意嗎?
uj5u.com熱心網友回復:
這是你想要達到的目標嗎?
$incoming是來自 javascript 代碼的 jsonString
$incomming = '{
"name":"A Name",
"_typography": {
"color": {
"hex":"#2196f3"
},
"text-transform":"uppercase",
"font-weight":"600"
}
}';
$a = json_decode($incomming, true);
echo var_export($a);
結果
array (
'name' => 'A Name',
'_typography' =>
array (
'color' =>
array (
'hex' => '#2196f3',
),
'text-transform' => 'uppercase',
'font-weight' => '600',
),
)
uj5u.com熱心網友回復:
唯一的變化是您應該將 true 添加到 json_decode 并使用 var_export 來獲取 php 陣列字串。如果你想得到方括號,你可以撰寫一些自定義字串生成器代碼。
function convert_js_object_to_php() {
// Getting the JS object
$object = $request->get_header('js_object');
// Decoding it to a PHP object
$output = json_decode($object, true);
if ($output) {
return var_export($output, true);
}
return false;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505603.html
標籤:javascript php
上一篇:文本檔案不正確的tell()位置
