查找数组中的常用单词

时间:2015-07-27 17:44:03

标签: php arrays string multidimensional-array associative-array

我有字符串

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
)

2 个答案:

答案 0 :(得分:2)

这应该适合你:

首先在每行的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);

答案 1 :(得分:0)

$arr = explode("\n",$array);

$desireArray = array();
foreach($arr as $value)
{
    $val = explode("(",$value);
    $desireArray[trim($val[0])] = trim($val[1],")");
}

print_R($desireArray);