php循环数组

时间:2011-11-22 01:22:20

标签: php arrays loops

我有一个包含“331,554,22”等数字的数组,或者它可能是“45”,假设该数组被称为$numbers

我想循环遍历数组,并为其中的每个数字或条目执行类似

的SQL查询
UPDATE members SET x=1 where id=$numbers[x]

有人可以帮助我吗?

更新:另外,假设我将查询值存储在名为nums的数据库的文本字段中,它看起来像是例如。 “45,656,23”,如何将其转换为数组格式?

4 个答案:

答案 0 :(得分:2)

如果可验"331,554,22"不是数组(字符串), 首先爆炸

$numbers = explode(',',$numbers);

然后。

Foreach:

 foreach ($numbers as $number)
        {
          //query like  SET x=1 where id=$number
        }

对于:

    for($i = 0; $i < count($numbers); $i++)
    {
       //query like  SET x=1 where id=$numbers[$i]
    }

如果x始终为1,则可以使用

$query = "UPDATE table SET x = 1 WHERE id  IN(" . implode(',',$numbers)  . ")"

如果$numbers变量是字符串,并且x对于每个ID都是1,请忘记我写的所有内容并仅尝试此操作:)

$query = "UPDATE table SET x = 1 WHERE id  IN({$numbers})"

答案 1 :(得分:1)

foreach($numbers as $number) {
  $sql = "UPDATE some_table SET X = 1 WHERE id = ".$number
}

希望有所帮助

答案 2 :(得分:0)

$query = "UPDATE members SET x=1 WHERE id IN(".implode( ",", $numbers).")";
  

它是一个字符串,所以,是的,我想是爆炸。

$query = "UPDATE members SET x=1 WHERE id IN({$numbers})";

答案 3 :(得分:0)

<?php

$numbers = array(25, 658, 968, 548, 698, 365);

foreach($numbers as $number){
 echo "UPDATE members SET x=1 where id=$number\n";
}

?>

<强>输出

 UPDATE members SET x=1 where id=25 
 UPDATE members SET x=1 where id=658
 UPDATE members SET x=1 where id=968 
 UPDATE members SET x=1 where id=548 
 UPDATE members SET x=1 where id=698 
 UPDATE members SET x=1 where id=365