search

Home  >  Q&A  >  body text

求段php 替换输出的代码

循环那部分一直写不对

要求如下
读取a.txt 内容是
111,2222
333,4444
555,7777
这样的格式

如果$goods_id的值 等于其中一行前面的值 那么转换成后面的输出,比如 $goods_id=111,那么进行替换后输出$goods_id=2222

黄舟黄舟2818 days ago296

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-10 15:30:24

    $goods_id = 111;
    
    $handle = fopen("f:/test.txt", "r");
    while (!feof($handle)) {
        $line = fgets($handle, 4096);
        //echo $line."<br>";
        $str = explode(",",$line);
    
        if($str[0] == $goods_id ){
            echo $str[1];
        }
    }
        fclose($handle);
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 15:30:24

    `

    function getGoodsIpMap()
    {
        $fh = fopen('a.txt', 'r');
        $goodsMap = array();
        while($line=fgets($fh)!==false)
        {
            if(empty($line))
            {
                continue;
            }
            list($oldId, $newId) = explode(',',trim($line));
            $goodsMap[$oldId] = $newId;
        }
        fclose($fh);
    }
    
    $goodsIdMap = getGoodsIpMap();
    $newId = isset($goodsIdMap[$goodsId]) ? $goodsIdMap[$goodsId] : $goodsId;
    

    `

    reply
    0
  • Cancelreply