3 回答

TA貢獻1784條經驗 獲得超9個贊
您可以使用preg_match_all
(正則表達式)和array_combine
:
使用正則表達式:
$str = "php/127/typescript/12/jquery/120/angular/50";
#match string
preg_match_all("/([^\/]*?)\/(\d+)/", $str, $match);
#then combine match[1] and match[2]?
$result = array_combine($match[1], $match[2]);
print_r($result);
演示(帶步驟): https:?//3v4l.org/blZhU

TA貢獻1921條經驗 獲得超9個贊
一種方法可能是preg_match_all分別從路徑中提取鍵和值。然后,使用array_combine構建哈希圖:
$str = "php/127/typescript/12/jquery/120/angular/50";
preg_match_all("/[^\W\d\/]+/", $str, $keys);
preg_match_all("/\d+/", $str, $vals);
$mapped = array_combine($keys[0], $vals[0]);
print_r($mapped[0]);
這打?。?/p>
Array
(
[0] => php
[1] => typescript
[2] => jquery
[3] => angular
)

TA貢獻1798條經驗 獲得超7個贊
您可以explode()與for()Loop 一起使用,如下所示:-
<?php
$str = 'php/127/typescript/12/jquery/120/angular/50';
$list = explode('/', $str);
$list_count = count($list);
$result = array();
for ($i=0 ; $i<$list_count; $i+=2) {
$result[ $list[$i] ] = $list[$i+1];
}
print_r($result);
?>
輸出:-
Array
(
[php] => 127
[typescript] => 12
[jquery] => 120
[angular] => 50
)
此處演示:- https://3v4l.org/8PQhd
- 3 回答
- 0 關注
- 172 瀏覽
添加回答
舉報