简体   繁体   中英

How to replace specific array string values with corresponding numbers in PHP?

I have an array with some repeating string values. How to replace these string values (as a whole, because some words are repeated in others strings) with corresponding specific numeric values, as bellow?

deloc        = 1
foarte puţin = 2
mediu        = 3
mult         = 4
foarte mult  = 5

This is the array (example):

array = (
    "tensionat"     => "mediu",
    "trist"         => "mult",
    "melancolic"    => "deloc",
    "fara_speranta" => "foarte puțin",
    "nefolositor"]  => "deloc",
    "ingrijorat"    => "foarte mult",
    "amarat"        => "deloc",
    "anxios"        => "mediu"
);

How can this

Try this

$data = array (
    "tensionat"     => "mediu",
    "trist"         => "mult",
    "melancolic"    => "deloc",
    "fara_speranta" => "foarte puțin",
    "nefolositor"   => "deloc",
    "ingrijorat"    => "foarte mult",
    "amarat"        => "deloc",
    "anxios"        => "mediu"
);

$repl = array (
    'deloc'        => 1,
    'foarte puţin' => 2,
    'mediu'        => 3,
    'mult'         => 4,
    'foarte mult'  => 5,
);

$result = array ();

foreach ($data as $key => $value) {
    $result[$key] = !empty($repl[$value]) ? $repl[$value] : $value;
}

print_r($result);

Output:

Array
(
    [tensionat] => 3
    [trist] => 4
    [melancolic] => 1
    [fara_speranta] => foarte puțin
    [nefolositor] => 1
    [ingrijorat] => 5
    [amarat] => 1
    [anxios] => 3
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM