[英]How to convert a JavaScript object to a PHP array and get the raw string?
在我的應用程序中,我需要將 JavaScript Object 轉換為以文本字符串形式返回的原始 PHP 數組。 我會調用 API 來做到這一點。 我不需要操縱數組。 在我的 JavaScript 應用程序中,我只需要簡單的 PHP object 字符串,如下所示。 (比如使用這個: https://wtools.io/convert-js-object-to-php-array )
JavaScript object 是:
{
"name":"A Name",
"_typography": {
"color": {
"hex":"#2196f3"
},
"text-transform":"uppercase",
"font-weight":"600"
}
}
我如何將 JavaScript Object 發送到 PHP ZC1C425268E68385D1AB5074F1C
JSON.stringify(jsObject);
我需要的字符串 output:
[
"name" => "A Name",
"_typography" => [
"color" => [
"hex" => "#2196f3"
],
"text-transform" => "uppercase",
"font-weight" =>"600"
]
]
我嘗試的是首先將json_decode
object json_decode 到 PHP ZA8CFDE6331BD59EB2AC96F891 然后嘗試將其作為字符串返回。 但沒有機會。 要么我得到一個 Js Object 要么完全得到其他東西。 我沒有更多的想法了。
我的嘗試
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;
}
你有什么主意嗎?
這是你想要達到的目標嗎?
$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',
),
)
唯一的變化是您應該將 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.