0

为什么不给出正确的退出代码?

我的完整代码:

<?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] => all
[1] => forg
[2] => sub

数组(
[0] => 110
[1] => 2
[2] => 1

但它是这样的:

数组
(
[0] => subsub0
[1] = > forg
[2] => sub
)
数组
(
[0] => 110
[1] => 2
[2] => 1
)

我该怎么办?

演示: http: //phpfiddle.org/main/code/srj-k3d

4

4 回答 4

0

You can try to use array_replace() like that: Bit more difficult to understand perhaps, but works ;)

$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);
?>
于 2013-01-31T15:48:40.037 回答
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");

于 2013-01-31T15:46:41.057 回答
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 按照您发送它们的顺序搜索字符串。因此,如果在您的情况下您正在搜索1and then 110,它将替换到达.1110

如果您替换第110一个,它将按预期替换。

于 2013-01-31T15:43:41.937 回答
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)。

于 2013-01-31T15:44:23.623 回答