我有以下值:如何使用循環從字符串中創建數組?
$attached_products = "1,4,3";
我想打一個數組,看起來像:
$selected = array(1, 4, 3);
使用循環與我$attached_products
。
我有以下值:如何使用循環從字符串中創建數組?
$attached_products = "1,4,3";
我想打一個數組,看起來像:
$selected = array(1, 4, 3);
使用循環與我$attached_products
。
這可以用循環完成,但有一個更簡單的方法。
您可以使用explode
函數[php docs]圍繞逗號打破字符串。這會給你一串數字。您可以通過應用intval
[php docs]使用array_map
[php docs]將每個字符串轉換爲整數。
$attached_products = "1,4,3";
$selected_strings = explode(',', $attached_products); # == array('1', '4', '3')
$selected = array_map('intval', $selected_strings); # == array(1, 4, 3)
您使用explode()
爲:
$selected = explode(", ", $attached_products);
如果有也可能沒有逗號後是可以的空白,你可以使用preg_split()
。
$selected = preg_split(/,\s*/, $attached_products);
另外,您可以使用explode()
,trim()
和array_map()
。
$selected = array_map('trim', explode(',', $attached_products));
如果他們必須是整數,通過intval()
映射。
感謝您的回覆@Jeremy Banks,嗯,是輸出等於數組(1,4,3)? – Emkey
'intval'需要引用。 – alex
@Emkey:我的值是字符串,不是整數。我修正了這個問題。現在他們是一樣的。 –