如何在PHP中按字符将数组拆分为关联数组[重复]
Posted
技术标签:
【中文标题】如何在PHP中按字符将数组拆分为关联数组[重复]【英文标题】:How to split an array into associative array by character in PHP [duplicate] 【发布时间】:2020-12-26 06:56:26 【问题描述】:我已经构建了一个程序,该程序从一个充满字符串的数组中获取数据,并将数据转换为适当格式化的数组。这是原始数组:
$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
)
)
在这里,我认为我应该将数组更改为关联键值对数组,并认为如果我能找到一种方法将数组通过字符分割转换为所述关联数组,那将是相对简单的,在本例中为“:”。
最后,我希望数组看起来像:
'action' => '',
'quantity' => '',
'item_code' => '',
'product_name' => '',
...等等
我曾尝试使用 array_column 和 array_combine 函数,但我对 php 还比较陌生,但运气不佳。 非常感谢任何帮助!
【问题讨论】:
使用explode()
和;
分隔符来获取字段。遍历字段并使用explode()
和:
分隔符来获取关键字和值。
其实很简单:repl.it/@FelipeMartins15/WittySelfreliantWorkspaces#main.php
【参考方案1】:
您可以在搜索替换后使用 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',
),
)
【讨论】:
如果任何值包含=
或&
,这将不起作用。以上是关于如何在PHP中按字符将数组拆分为关联数组[重复]的主要内容,如果未能解决你的问题,请参考以下文章