4 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
這可能是您所需要的:
<?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貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
很簡(jiǎn)單:
$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);
在此處撥動(dòng)。

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以使用 :
$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
您將獲得單獨(dú)的集合array()

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個(gè)贊
只是為了好玩,還有一種方法可以做到這一點(diǎn):
$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);
基本上,我們用兩個(gè)可能的分隔符 : 或 ; 后跟空格來(lái)分割該行。
然后 array_chunk 函數(shù)將鍵和值分組在一起,我們?yōu)槊恳恍械玫饺缦滤镜膬?nèi)容:
Array
(
[0] => Array
(
[0] => action
[1] => Added
)
[1] => Array
(
[0] => amount
[1] => 1
)
* * *
通過(guò)擴(kuò)展和映射上面的數(shù)組,我們得到它的旋轉(zhuǎn)版本,如下所示:
Array
(
[0] => Array
(
[0] => action
[1] => amount
* * *
)
[1] => Array
(
[0] => Added
[1] => 1
* * *
)
)
我們現(xiàn)在可以擴(kuò)展這個(gè)數(shù)組并將其傳遞給array_combine函數(shù),這樣我們就有了一個(gè)很好的關(guān)聯(lián)數(shù)組,其中填充了所需的鍵和值。
然后我們映射所有的線,這樣我們就得到了格式良好的結(jié)果。
- 4 回答
- 0 關(guān)注
- 319 瀏覽
添加回答
舉報(bào)