經過長時間的研究,沒有找到解決方案。所以stackoverflow是我最后的希望。
在 PHP 中,我需要一個決議器來從 postgreSQL 資料庫中獲取資料。
字串結構是這樣的:
"keytext {this is my value text 1} key with multi words {value text 2} another key {key_value number 3}"
所以我們有鍵(可以由幾個單詞組成)和花括號中的值。
我認為,這種資料型別來自 TCL。
我們如何在 PHP 7/8 中將此字串轉換為 JSON-String 或陣列?
非常感謝您幫助我!
uj5u.com熱心網友回復:
不是一個完美的方法,但它的作業。
$string = "keytext {this is my value text 1} key with multi words {value text 2} another key {key_value number 3}";
$results = explode('{', $string);
$newArray = $values = [];
foreach ($results as $result){
if (strpos($result, '}') !== false) {
$values[] = explode('}', $result)[0];
$keys[] = explode('}', $result)[1];
} else {
$keys[] = $result;
}
}
$newArray = [];
foreach ($keys as $index => $key) {
if ($key !== '' && isset($values[$index])){
$newArray[$key] = $values[$index];
}
}
return $newArray;
uj5u.com熱心網友回復:
看一下這個
$str = "keytext {this is my value text 1} key with multi words {value text 2} another key {key_value number 3}";
$chars = str_split($str);
$result_arr = [];
$make_arr_key = true;
$make_arr_key_val = false;
$arr_key = '';
$arr_key_val = '';
foreach ($chars as $char) {
if($char == '{') {
$make_arr_key = false;
$arr_key_val = '';
$make_arr_key_val = true;
}
if($char == '}') {
$result_arr[trim($arr_key)] = trim($arr_key_val);
$arr_key = '';
$make_arr_key = true;
$make_arr_key_val = false;
}
if($make_arr_key) {
if($char != '}'){
$arr_key .= $char;
}
}
if($make_arr_key_val) {
if($char != '{') {
$arr_key_val .= $char;
}
}
}
print_r($result_arr);
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/317021.html
