duanpasi6287
2013-05-15 07:17
采纳率: 100%
浏览 41
已采纳

在mysql更新查询中使用两个具有不同键的数组

I have a array like this

$outputs:
  269 => string '   SUN: 2.495' (length=13)
  510 => string '   SUN: 1.416' (length=13)

Another Array like this

$filenames:
  0 => string 'Hi35
' (length=5)
  1 => string 'He_41
' (length=6)

And to update the respective values i tried writing a code like

foreach($outputs as $key => $value){
    $sql = "UPDATE Store SET D='".$value."' WHERE `Index` = '".$filenames[$key]."'";
    mysql_query($sql);
}

But then there is no $filenames[$key] value, because the key value for $outputs starts with 269. This is only one case, the key value could be anything.

I also tried the other way around. i.e.

I combined both the array first

$arr3 = array_combine($outputs, $filenames);

And then tried to Put the combined array in SQL query like

foreach($arr3 as $key => $value){
    $sql = "UPDATE Store SET D='".$key."' WHERE `Index` = '".$value."'";
    mysql_query($sql);
}

BUT this dint work.. A help from your side will really be appreciated...

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanluan3651 2013-05-15 08:09
    已采纳

    You can do something like this

    $outputs = array(
      '269' => 'SUN: 2.495',
      '510' => 'SUN: 1.416'
      );
    
    $filenames = array(
      '0' => 'Hi35',
      '1' => 'He_41'
    );
    
    $array_complete = array_combine($filenames, $outputs);
    
    foreach($array_complete as $key => $val)
    {
        echo "UPDATE Store SET D='".$val."' WHERE `Index` = '".$key."'" . '<br>';
    }
    

    This will output

    UPDATE Store SET D='SUN: 2.495' WHERE `Index` = 'Hi35'
    UPDATE Store SET D='SUN: 1.416' WHERE `Index` = 'He_41'
    

    Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO

    打赏 评论
  • douzhi7082 2013-05-15 07:24

    Your code doesn't look good at all mate, but here is a hack for that:

    $num_outputs = count($outputs);
    
    $index = 0;
    foreach($outputs as $key => $value) {
        $sql = "UPDATE Store SET D='".$value."' WHERE `Index` = '".$index."'";
        mysqli_query($sql);
        $index++;
    }
    
    打赏 评论

相关推荐 更多相似问题