duanpo2813 2012-05-01 22:13
浏览 185
已采纳

PHP foreach成功循环在循环开始时重新分配变量

I have a loop where it query's mysql for a search but the search will change by the end of the query. What i found out with my coding is which i did not now is that i can't reassign a variable to a new search query, or not correctly anyways.

I have added echo's to see what it's doing.

Lets say John is assigned to $preg_split

What i am trying to do is to match a character with a database if one the first characters in the database for example J matches then assign the second character from $pre_split which is o so $char would be jo

So the variable $char in the beginning should be updated with jo

Instead for some reason which i'm sure that i just did not write my code correct is that it echo's o an not jo..

So i'm a bit puzzled why its the second character and not the first.

$NG_implode = implode("", $preg_split);

$NG_split = str_split($NG_implode, 1);
$i = '0';
$ia = '1';
$ib = '0';
$ic = '1';
$char = $NG_split[$ib];


foreach ($NG_split as $char)
{

    $NG_select_like = "SELECT word FROM checklist_filter WHERE word LIKE '".$char."%'";
    $NG_query = mysql_query($NG_select_like) or die(mysql_error());
    $NG_row = mysql_fetch_row($NG_query);
    $chars = str_split($char, 1);
    $row = str_split($NG_row[0], 1);
        if ($chars[$i] == $row[$i])
        {

            $char = $char.$NG_split[$ia];

            $ia++;
            $i++;
            if ($char == $NG_row[0]){break;}
            }else{$ib++; $char = $NG_split[$ib];}

    }
  • 写回答

1条回答 默认 最新

  • dongyuanliao6204 2012-05-01 22:26
    关注

    $char gets set to the next value of $NG_split in every new iteration of the foreach loop , so the value you're assigning to $char inside your foreach loop won't be there anymore next time. Can't you simply do this?

    <?php
    $str = "John";
    $len = strlen($str);
    
    $arr = array();
    $i = 0;
    while($i < $len) { 
        $arr[] = substr($str,0,$len-$i);
        $i++;
    } 
    
    var_dump($arr);
    ?>
    

    Now if you iterate over $arr you should be able to build the queries you're interested in. There's probably an even more efficient way to get the results you're looking for using a regular expression in MySQL but it would help if you could share a bit more about your use case for this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?