问题描述
我构建了一个程序,该程序从充满字符串的数组中获取数据,然后将数据转换为适当格式的数组。这是原始数组:
var maximizeButton = view.down('[type="maximize"]')
if (maximizeButton) {
maximizeButton.setBind({
disabled: '{!isMaxWinAllowed}'
});
}
这是数据格式正确的新数组。
$arr = array(
"action: Added; quantity: 1; item_code: RNA1; product_name: Mens Organic T-shirt; colour: White; size: XL","action: Subtracted; quantity: 7; item_code: RNC1; product_name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y","action: Added; quantity: 20; item_code: RNV1; product_name: Gift Voucher; style: Mens; value: £20",);
在这里,我认为我应该将数组更改为关联的键值对数组,并认为如果我能找到一种方法,可以通过将字符分割为数组将其转换为所述的关联数组,则相对简单,在这种情况下为“:”。
最后,我希望数组看起来像这样:
Array
(
[0] => Array
(
[0] => action: Added
[1] => quantity: 1
[2] => item_code: RNA1
[3] => product_name: Mens Organic T-shirt
[4] => colour: White
[5] => size: XL
)
[1] => Array
(
[6] => action: Subtracted
[7] => quantity: 7
[8] => item_code: RNC1
[9] => product_name: Kids Basic T-shirt
[10] => colour: Denim Blue
[11] => size: 3-4y
)
[2] => Array
(
[12] => action: Added
[13] => quantity: 20
[14] => item_code: RNV1
[15] => product_name: Gift Voucher
[16] => style: Mens
[17] => value: £20
)
)
...等等。
我曾尝试使用array_column和array_combine函数,但在PHP相对较新的地方我运气并不好。 任何帮助将不胜感激!
解决方法
搜索替换后,您可以使用parse_str。
<?php
$arr = array(
"action: Added; quantity: 1; item_code: RNA1; product_name: Mens Organic T-shirt; colour: White; size: XL","action: Subtracted; quantity: 7; item_code: RNC1; product_name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y","action: Added; quantity: 20; item_code: RNV1; product_name: Gift Voucher; style: Mens; value: £20",);
$arr = array_map(function($v) {
parse_str(str_replace([': ','; '],['=','&'],$v),$result);
return $result;
},$arr);
var_export($arr);
输出:
array (
0 =>
array (
'action' => 'Added','quantity' => '1','item_code' => 'RNA1','product_name' => 'Mens Organic T-shirt','colour' => 'White','size' => 'XL',),1 =>
array (
'action' => 'Subtracted','quantity' => '7','item_code' => 'RNC1','product_name' => 'Kids Basic T-shirt','colour' => 'Denim Blue','size' => '3-4y',2 =>
array (
'action' => 'Added','quantity' => '20','item_code' => 'RNV1','product_name' => 'Gift Voucher','style' => 'Mens','value' => '£20',)