2017-02-22 45 views
-4

我需要将一些单词改为数字。示例如下─是php str_replace意外字符替换

$status= str_replace(array("canceled","shipped","processing","complete","pending_payment","closed","fraud","holded","payment_review","pending"),array(4,6,2,10,1,12,0,1,1,2),$sale["status"]); 

但如果意外的话来自DB我想将其更改为0

这可能吗?

+3

这是可能的,你有什么尝试? – omxv

+0

使用简单的switch语句,更容易阅读和维护,并提供'default'指令。 – arkascha

+0

其实我使用它,如果情况是这样的; elseif的状态1 =如果 “待定”,然后 状态= 2 否则 状态= 0 结束,但我不知道我怎么能与str_replace函数 – Humanwere

回答

1

你可以做这样的事情:

$statuses = [ 
     "canceled" => 4, 
     "shipped" => 6, 
     "processing" => 2, 
     "complete" => 10, 
     "pending_payment" => 1, 
     "closed" => 12, 
     "fraud" => 0, 
     "holded" => 1, 
     "payment_review" => 1, 
     "pending" => 2, 
    ]; 

    $status = 0; 

    if (isset($statuses[$sale["status"]])) { 
     $status = $statuses[$sale["status"]]; 
    } 

这样您就可以轻松查看哪些字符串值映射到哪个号码。将$ status变量的默认值设置为0.如果给出的状态字符串存在于“statusmap”中,则替换$ status变量。

0

试试这个,

$status_words = array("canceled", "shipped", "processing", "complete", "pending_payment", "closed", "fraud", "holded", "payment_review", "pending"); 
$status_ints = array(4, 6, 2, 10, 1, 12, 0, 1, 1, 2); 
$status = (in_array(trim($sale["status"]), $status_words) ? 
      str_replace($status_words, $status_ints, trim($sale["status"])) : ''); 

试试看吧,这应该工作。