根据另一个关键值更改键值

时间:2014-08-05 18:25:36

标签: php arrays foreach

我有这样的功能:

foreach($data as $line) {
    if(substr($line,0,1) == "A") {
        if(!$first) {
            $parts = explode(chr(9),$line);

            //echo "<pre>"; print_r($parts); echo "</pre>";

打印时返回多个这样的数组:

Array
(
    [0] => A
    [1] => 100_1
    [2] => 0
    [3] => 1188
    [4] => 0
)

Array
(
    [0] => A
    [1] => 100_2
    [2] => 0
    [3] => 1188
    [4] => 0
)

Array
(
    [0] => A
    [1] => 100_3
    [2] => 0
    [3] => 1186
    [4] => 0
)

Array
(
    [0] => A
    [1] => 101_2
    [2] => 0
    [3] => 1188
    [4] => 0
)

Array
(
    [0] => A
    [1] => 302
    [2] => 0
    [3] => 1161
    [4] => 0
)

是否有可能只有&#39;选择值为_1,2,3的键([1]),(如果存在) 并用相同的值替换键([2]),结果将是:

Array
(
    [0] => A
    [1] => 100_1
    [2] => 1
    [3] => 1187
    [4] => 0
)

Array
(
    [0] => A
    [1] => 100_2
    [2] => 2
    [3] => 1188
    [4] => 0
)

Array
(
    [0] => A
    [1] => 100_3
    [2] => 3
    [3] => 1186
    [4] => 0
)

Array
(
    [0] => A
    [1] => 101_2
    [2] => 2
    [3] => 1188
    [4] => 0
)

Array
(
    [0] => A
    [1] => 302
    [2] => 0
    [3] => 1161
    [4] => 0
)

我试图制作这样的大量条目,但它们不起作用(我无法获得正确的密钥):

foreach($parts as $key => $value) {

    if ($value == '100_1') {$parts[$key] = '1';};
    if ($value == '100_2') {$parts[$key] = '2';};
    if ($value == '100_3') {$parts[$key] = '3';}}

但这将是纯粹的疯狂,因为有超过50种不同的值和数组,任何帮助都会受到极大的欢迎。

1 个答案:

答案 0 :(得分:0)

类似的东西:

foreach($data as $line) {
    if(substr($line,0,1)=="A") {
        if(!$first) {
            $parts = explode(chr(9), $line);
            list($num1, $num2) = explode('_', $parts[1]);
            $parts[2] = isset($num2) ? $num2 : $parts[2];
        }
    }
}