'Array to string conversion

$replacements = array(
    '{order_id}' => $order_id, 
    '{site_url}' => $settings["site_url"], 
    '{email}' => $user_email, 
    '{last_name}' => $last_name, 
    '{phone}' => $phone, 
    '{order_total}' => currency_format($order_total), 
);

    foreach($replacements as $param => $value){
    $sms = str_replace($param, $value, $db2->f('sms'));
    $user_to = str_replace($param, $value, $db2->f('user_to'));
    $user_from = str_replace($param, $value, $db2->f('user_from'));
    $user_subject = str_replace($param, $value, $db2->f('user_subject'));
    $user_body = str_replace($param, $value, $user_body);
    $admin_to = str_replace($param, $value, $db2->f('admin_to'));
    $admin_from = str_replace($param, $value, $db2->f('admin_from'));
    $admin_subject = str_replace($param, $value, $db2->f('admin_subject'));
    $admin_body = str_replace($param, $value, $db2->f('admin_body'));
}

What is the problem? Why can't work? Array to string conversion....

Can anyone suggest how to reduce the number of lines of code in such a case?



Solution 1:[1]

$replacements = array(
    '{order_id}' => $order_id, 
    '{site_url}' => $settings["site_url"], 
    '{email}' => $user_email, 
    '{last_name}' => $last_name, 
    '{phone}' => $phone, 
    '{order_total}' => currency_format($order_total), 
);

$templates = array(
    'sms' => $db2->f('sms'), 
    'user_to' => $db2->f('user_to'), 
    'user_from' => $db2->f('user_from'), 
    'user_subject' => $db2->f('user_subject'), 
    'user_body' => $db2->f('user_body'), 
    'admin_to' => $db2->f('admin_to'), 
    'admin_from' => $db2->f('admin_from'), 
    'admin_subject' => $db2->f('admin_subject'), 
    'admin_body' => $db2->f('admin_body')
);

foreach($templates as $way => $tmp){
    $templates[$way] = strtr($tmp, $replacements);
}

Solution 2:[2]

You're overwritting $user_body each time you loop. Try that:

$replacements = array(
    '{order_id}' => $order_id, 
    '{site_url}' => $settings["site_url"], 
    '{email}' => $user_email, 
    '{last_name}' => $last_name, 
    '{phone}' => $phone, 
    '{order_total}' => currency_format($order_total), 
);

$user_body = $db2->f('user_body');
foreach($replacements as $param => $value){
    $user_body = str_replace($param, $value, $user_body);
}

echo $user_body;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luntegg
Solution 2 Bgi