[英]split strings into nested array by matching sub string
我需要將字符串拆分成類似這樣的嵌套數組。 實際數據的一小部分
aaa100
和bbbbbbbb100
產品進口有數千種產品。 每個產品代碼都由以下內容組成:
xxx product type
yyy size
zzz colour
因此,您具有類似xxxx
, xxxxyy
, xxxxzz
或xxxxyyzz
。
AAA100B // product type AAA with size 100 and colour blue
AAA200B // product type AAA with size 200 and colour blue
AAA100G // product type AAA with size 100 and colour green
BBB100B // product type BBB with size 100 and colour blue
有些沒有顏色,有些沒有尺寸。 可能有些將沒有“匹配項”,而只是一個單獨的代碼。
最后一個字符(或兩個)通常是一種顏色。 顏色可以是以下任意一種。 (顏色代碼永遠不會在字符串的末尾出現)
BK, GY
B, G, O, P, R, S
假定數字為大小,如果數字的長度/寬度為00-00
形式,否則為單個大小00
這個問題的開始很粗糙,實際上在那里(擴展和合並是框架的一部分,所以只在其中進行了入侵) http://codepad.viper-7.com/Wp19g2
嗯,我猜最明顯的方法(雖然效率不高)是當您到達數字記錄時,將您的代碼字符串循環遍歷字母直到找到一個數字(將直到該點的所有字母都記錄為產品類型)該值及其后的每個數字,直到您再次輸入字母,然后開始記錄顏色。 當然,這是假定顏色和產品類型不包括數字!
$product_size = ""; $product_type = ""; $product_color = "";
for ($i = 0; $i < strlen ( $code ); $i++ ) {
if ( !is_numeric ( $code [ $i ] ) ) {
if ( $product_size == "" ) $product_type .= $code [ $i ];
else $product_color .= $code [ $i ]
} else $product_size .= $code [ $i ];
}
擁有分隔符是一個不錯的設計選擇。 我的解決方案的一個問題是,如果沒有產品尺寸,那么它將永遠不會記錄顏色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.