while ($row = tep_db_fetch_array($r)) {
    $products_id = $row['products_id'];
    $ca = explode(',', $row['color']);
    foreach ($ca as $key => $c) {
        $ca[$key] = trim($c);
    }
    $color_pattern_id = array();
    foreach ($ca as $c) {
        if ($c != '' && isset($colors[$c])) {
            $color_pattern_id[] = $colors[$c];
        }
    }
    if (count($color_pattern_id) > 0) {
        $class_pm->setColorPattern($products_id, $color_pattern_id);
    }
    $ma = explode(',', $row['material']);
    foreach ($ma as $key => $m) {
        $ma[$key] = trim($m);
    }
    $products_materials_id = array();
    foreach ($ma as $m) {
        if ($m != '' && in_array($m, $materials)) {
            $products_materials_id[] = array_search($m, $materials);
        }
    }
    if (count($products_materials_id) > 0) {
        $class_pm->setProductMaterials($products_id, $products_materials_id);
    }
}
echo 'Done';
tep_db_close();
while ($r = tep_db_fetch_array($dbq)) {
    if ($r['finishing_goldplate'] == '1' && !in_array($r['products_id'], $goldplated)) {
        $goldplated[] = $r['products_id'];
    }
    if (!isset($products[$r['products_id']])) {
        $products[$r['products_id']] = array();
    }
    if (!is_null($r['attribute_material_id']) && !in_array($r['attribute_material_id'], $products[$r['products_id']])) {
        $products[$r['products_id']][] = $r['attribute_material_id'];
    }
}
//echo "<pre>";var_dump($products);
//die();
foreach ($products as $pid => $materials_id) {
    //    echo "$pid : ";print_r($materials_id);
    //    echo "<br
    if (count($materials_id) > 0) {
        if (in_array($pid, $goldplated)) {
            $key = array_search('1', $materials_id);
            if ($key !== false) {
                unset($materials_id[$key]);
            }
            $materials_id[] = '17';
        }
        $class_pm->setProductMaterials($pid, $materials_id);
        $class_cp->setParams($pid, 'M');
        echo "Product {$pid} , materials_id's (" . implode(",", $materials_id) . ") added <br/>";
    } else {
        echo "No Material found: {$pid}<br/>";
    }
}