简体   繁体   中英

Search for matching values in a table and replace with array keys

I want to loop through my table, compare the values of a column with a list of array values so that if there's a match, i replace the value in the table with the array keys. Ideally, i could have done it this way(search/replace) but i have a whole lot of values. So I want to include the array in an inc file.

while($row = $db->fetchAssoc()){
            $fields_count = 0;
            foreach($row as $key => $val){
                if($fields_count++ > 0)
                $val = str_replace("Appliances > Air Conditioners","111,233", $val);
                $val = str_replace("Appliances > Air Purifiers","154,234", $val);
                $val = str_replace("Appliances > Appliance Accessories > Air Conditioner Accessories","123,235", $val);

this is my array and keys, how do i get my loop done, so that i can search for matching values in the array and replace them with the array keys in my table?

$arr_categories = array( 
    "111,233"=>"Appliances > Air Conditioners",
    "154,234"=>"Appliances > Air Purifiers",
    "123,235"=>"Appliances > Appliance Accessories > Air Conditioner Accessories");
$arrCategories = array( 
    '111,233' => 'Appliances > Air Conditioners',
    '154,234' => 'Appliances > Air Purifiers',
    '123,235' => 'Appliances > Appliance Accessories > Air Conditioner Accessories'
);

while ($row = $db->fetchAssoc()) {
    foreach ($row as &$column) {
        foreach ($arrCategories as $key => $category) {
            $column = str_replace($category, $key, $column);
        }
    }

    // Do something...
}

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