我有一个字符串:
Fragrances, Beauty & Health (153)
Skin Care (146)
Make Up (10)
Health Care & Instruments (1)
Hair Care (1)
我正在把它转换成一个数组:
$formatted = array_map('trim', preg_split("/[()]+/", $string, -1, PREG_SPLIT_NO_EMPTY));
结果:
Array
(
[0] => Fragrances, Beauty & Health
[1] => 153
[2] => Skin Care
[3] => 146
[4] => Make Up
[5] => 10
[6] => Health Care & Instruments
[7] => 1
[8] => Hair Care
[9] => 1
)
我应该怎么做才能达到想要的结果:
Array
(
[Fragrances, Beauty & Health] => 153
[Skin Care] => 146
[Make Up] => 10
[Health Care & Instruments] => 1
[Hair Care] => 1
)
这应该适用于您:
首先,每行只explode()
您的字符串,然后用array_map()
遍历每个元素,并用(
或)
将其拆分。
之后,您可以简单地使用array_column()
将第一列用作键,将第二列用作值。
<?php
$arr = array_column(array_map(function($v){
return array_map("trim", preg_split("/[()]+/", $v, -1, PREG_SPLIT_NO_EMPTY));
}, explode(PHP_EOL, $str)), 1, 0);
print_r($arr);
?>
输出:
Array
(
[Fragrances, Beauty & Health] => 153
[Skin Care] => 146
[Make Up] => 10
[Health Care & Instruments] => 1
[Hair Care] => 1
)
编辑:
你不能有重复的密钥,所以如果你想保留价值最高的密钥,你可以这样做:
$arr = array_map(function($v){
$arr = array_map("trim", preg_split("/[()]+/", $v, -1, PREG_SPLIT_NO_EMPTY));
if(!isset($arr[1]))
$arr[1] = 0;
return $arr;
}, explode(PHP_EOL, $str));
usort($arr, function($a, $b){
return $a[1] - $b[1];
});
$arr = array_column($arr, 1, 0);
print_r($arr);
$arr = explode("n",$array);
$desireArray = array();
foreach($arr as $value)
{
$val = explode("(",$value);
$desireArray[trim($val[0])] = trim($val[1],")");
}
print_R($desireArray);