4 回答
TA贡献1805条经验 获得超9个赞
这可能是您所需要的:
<?php
$arr = array(
"action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",
"action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",
"action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20"
);
foreach ($arr as $string) {
//Build array
preg_match_all("/ [ ]?([^:]+): ([^;]+)[ ;]? /x", $string, $p);
$array = array_combine($p[1], $p[2]);
//Print it or do something else with it
print_r($array);
}
TA贡献1802条经验 获得超10个赞
很简单:
$arr = array(
"action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",
"action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",
"action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",
);
$data = [];
foreach ($arr as $line) {
$newItem = [];
foreach (explode(';', $line) as $item) {
$parts = explode(':', $item);
$newItem[trim($parts[0])] = trim($parts[1]);
}
$data[] = $newItem;
}
print_r($data);
在此处拨动。
TA贡献1873条经验 获得超9个赞
您可以使用 :
$tempArray = array();
foreach($arr as $data){
$dataExplode = explode(';', $data);
$temp = array();
foreach($dataExplode as $key => $child){
$childExplode = explode(':', $child);
$temp[$childExplode[0]] = $childExplode[1];
}
array_push($tempArray, $temp);
}
print_r($tempArray); //to print array collection
您将获得单独的集合array()
TA贡献1816条经验 获得超4个赞
只是为了好玩,还有一种方法可以做到这一点:
$arr = array(
"action: Added; amount: 1; code: RNA1; name: Mens Organic T-shirt; colour: White; size: XL",
"action: Subtracted; amount: 7; code: RNC1; name: Kids Basic T-shirt; colour: Denim Blue; size: 3-4y",
"action: Added; amount: 20; code: RNV1; name: Gift Voucher; style: Mens; value: £20",
);
$result = array_map(function($line) {
return array_combine(...array_map(null, ...array_chunk(preg_split('/[:;]\s+/', $line), 2)));
}, $arr);
print_r($result);
基本上,我们用两个可能的分隔符 : 或 ; 后跟空格来分割该行。
然后 array_chunk 函数将键和值分组在一起,我们为每一行得到如下所示的内容:
Array
(
[0] => Array
(
[0] => action
[1] => Added
)
[1] => Array
(
[0] => amount
[1] => 1
)
* * *
通过扩展和映射上面的数组,我们得到它的旋转版本,如下所示:
Array
(
[0] => Array
(
[0] => action
[1] => amount
* * *
)
[1] => Array
(
[0] => Added
[1] => 1
* * *
)
)
我们现在可以扩展这个数组并将其传递给array_combine函数,这样我们就有了一个很好的关联数组,其中填充了所需的键和值。
然后我们映射所有的线,这样我们就得到了格式良好的结果。
- 4 回答
- 0 关注
- 200 浏览
添加回答
举报