php str_replace意外的char替换

时间:2017-02-22 12:54:56

标签: 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。

这可能吗?

1 个答案:

答案 0 :(得分: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变量。