为什么不给出正确的退出代码?
我的完整代码:
<?php
$numA_m = "2";
$res = '["110","2","1"]';
$numA_s = json_decode($res);
if ($numA_m == 1) {
$A_num_s = array("1", "2", "3", "4","110");
$A_nam_s = array("egh", "guide", "irl", "tic", "all");
}
if ($numA_m == 2) {
$A_num_s = array("1", "2","110");
$A_nam_s = array("sub", "forg","all");
}
$Rsp = str_replace($A_num_s, $A_nam_s, $numA_s);
$Rsp_In = str_replace($A_nam_s, $A_num_s, $Rsp);
echo '<pre>';
print_r($Rsp);
echo '<p>';
echo '<pre>';
print_r($Rsp_In);
?>
输出应为:
阵列(
[0] =&gt;所有
[1] =&gt; forg
[2] =&gt;子
)阵列(
[0] =&gt; 110个
[1] =&gt; 2
[2] =&gt; 1
)
但它是这样的:
阵列
(
[0] =&gt; subsub0
[1] =&gt; forg
[2] =&gt; sub
)阵列
(
[0] =&gt; 110个
[1] =&gt; 2
[2] =&gt; 1
)
我该怎么办?
答案 0 :(得分:0)
这会输出所需的结果
$numA_m = "2";
$res = '["110","2","1"]';
$numA_s = json_decode($res);
if ($numA_m == 1) {
$A_num_s = array("1", "2", "3", "4", "110");
$A_nam_s = array("egh", "guide", "irl", "tic", "all");
}
if ($numA_m == 2) {
$A_num_s = array("110", "2", "1"); // changed order
$A_nam_s = array("all", "forg", "sub");
}
$count = 1;
$Rsp = str_replace($A_num_s, $A_nam_s, $numA_s, $count);
$Rsp_In = str_replace($A_nam_s, $A_num_s, $Rsp, $count);
echo '<pre>';
print_r($Rsp);
echo '<p>';
echo '<pre>';
print_r($Rsp_In);
<强>解释强>
str_replace按照发送顺序搜索字符串。因此,如果您在搜索1
然后110
,则会在到达1
之前替换110
的所有出现次数。
如果您先替换110
,它将按预期更换。
答案 1 :(得分:0)
首先,str_replace
工作正常
您可以做的是替换数组中的顺序:
$A_num_s = array("110", "1", "2");
$A_nam_s = array("all", "sub", "forg");
在你的版本中,str_replace将“110”视为两个1(和一个0),并用“sub”(“subsub0”)替换它们。
根据更改后的订单,“110”将首先匹配,导致str_replace
按照您提供的顺序搜索您的模式($A_num_s
)。
答案 2 :(得分:0)
str_replace
按顺序替换,按顺序检查每个替换值的整个替换主题,例如:
http://php.net/manual/en/function.str-replace.php
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
所以,你需要做的就是在1之前替换110,否则首先替换110中的1:
$A_num_s = array("110", "2", "1");
答案 3 :(得分:0)
您可以尝试使用array_replace(): 或许有点难以理解,但有效;)
$numA_m = "2";
$res = '["110","2","1"]';
$numA_s = json_decode($res);
if ($numA_m == 1) {
$A_num_s = array("1", "2", "3", "4","110");
$A_nam_s = array("egh", "guide", "irl", "tic", "all");
}
if ($numA_m == 2) {
$A_num_s = array("1", "2","110");
$A_nam_s = array("sub", "forg","all");
}
$Rsp = array_replace($numA_s, $A_num_s, array_reverse($A_nam_s));
$Rsp_In = array_replace($Rsp, $A_nam_s, array_reverse($A_num_s));
echo '<pre>';
print_r($Rsp);
echo '<p>';
echo '<pre>';
print_r($Rsp_In);
?>