這是通過 simplexmlelement 從 CDATA 獲取值后的樣子
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}"
我嘗試在 google 中尋找解決方案,但我找不到可以將這組字串轉換為陣列的解決方案。
我希望這些資料轉換成這樣的陣列
["customertype"] = ["New"]
["Telephone"] = ["09832354544"]
等等等等或類似于陣列的樣子。提前致謝
uj5u.com熱心網友回復:
鑒于您的資料字串格式,您可以執行以下操作:
首先,洗掉括號{ }
然后使用,分隔符分解字串。
現在,您有包含例如customertype=New.
接下來是棘手的部分,結果字串看起來像一個查詢,所以我們將使用
parse_str()來創建一個關聯陣列:
結果將類似于以下內容:
array:9 [▼
0 => array:1 [▼
"customertype" => "New"
]
1 => array:1 [▼
"Telephone" => "09832354544"
]
2 => array:1 [▼
"CITY" => "Henfield"
]
這是代碼:
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
$rippedData = str_replace(["{", "}"],"", $data);
$singleData= explode(",", $rippedData);
$finalArray = [];
foreach($singleData as $string){
parse_str($string, $output);
$finalArray[] = $output;
}
uj5u.com熱心網友回復:
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
$stripped = str_replace(['{','}'], '', $data);
$explode = explode(', ', $stripped);
$output = [];
foreach ($explode as $value) {
$inner_explode = explode('=', $value);
$output[$inner_explode[0]] = $inner_explode[1];
}
var_dump($output);
結果是
array(9) {
["customertype"]=>
string(3) "New"
["Telephone"]=>
string(11) "09832354544"
["CITY"]=>
string(8) "Henfield"
["LASTNAME"]=>
string(1) "C"
["TicketNo"]=>
string(6) "123456"
["FIRSTNAME"]=>
string(4) "Alex"
["Id"]=>
string(8) "10001273"
["testfield"]=>
string(6) "123456"
["COMPANY"]=>
string(5) "Camp1"
}
uj5u.com熱心網友回復:
這應該有效,盡管可能有更好/更清晰的編碼方式。
$data = "{customertype=New, Telephone=09832354544, CITY=Henfield, LASTNAME=C, TicketNo=123456, FIRSTNAME=Alex, Id=10001273, testfield=123456, COMPANY=Camp1}";
// Replace squiggles
$replace_this = array("{","}");
$replace_data = str_replace($replace_this,"",$data);
// Explode and create array
$data_array = explode(',',$replace_data);
// Loop through the data_array
foreach($data_array as $value) {
// Explode the value on the equal sign
$explode_again = explode('=', $value);
// Create new array with correct indexes and values
$CDTA[trim($explode_again[0])] = $explode_again[1];
}
echo '<pre>' . var_export($CDTA, true) . '</pre>';
結果:
array (
'customertype' => 'New',
'Telephone' => '09832354544',
'CITY' => 'Henfield',
'LASTNAME' => 'C',
'TicketNo' => '123456',
'FIRSTNAME' => 'Alex',
'Id' => '10001273',
'testfield' => '123456',
'COMPANY' => 'Camp1',
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316079.html
