eozzy
eozzy

Reputation: 68660

Finding common words in an array

I have a string:

Fragrances, Beauty & Health (153)
    Skin Care (146)
    Make Up (10)
    Health Care & Instruments (1)
    Hair Care (1)

I'm converting it into an array:

$formatted = array_map('trim', preg_split("/[()]+/", $string, -1, PREG_SPLIT_NO_EMPTY));

Result:

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
)

... what should I do to achieve the desired result:

Array
(
    [Fragrances, Beauty & Health] => 153
    [Skin Care] => 146
    [Make Up] => 10
    [Health Care & Instruments] => 1
    [Hair Care] => 1
)

Upvotes: 1

Views: 449

Answers (2)

DINO U
DINO U

Reputation: 126

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

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

print_R($desireArray);

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

This should work for you:

First just explode() your string by each line, then go through each element with array_map() and split it either by ( or ).

After this you can simply use array_column() to use the first column as key and the second one as value.

<?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);

?>

output:

Array
(
    [Fragrances, Beauty & Health] => 153
    [Skin Care] => 146
    [Make Up] => 10
    [Health Care & Instruments] => 1
    [Hair Care] => 1
)

EDIT:

You can't have duplicate keys, so if you want to keep the one with the highest value you could do something like this:

$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);

Upvotes: 2

Related Questions