dongtuojuan8998 2012-12-14 17:12
浏览 45
已采纳

插入数组键作为字段值 - mysql / php

I have multiple named keys and each gets assigned a value between 0 and 5.

I have created an array and array filter to keep only the key that has been assigned a value > 0. Dropping any 0 value pairs from the array.

What I need is a way to insert the key name and the value assigned as separate fields in the same table.

The column names are skill_name and value.

The array after submit:

Array ( [Academics] => 2 [Animal_Ken] => 3 [Athletics] => 2 [Awareness] => 0 [Blood_Sense] => 0 [Brawl] => 0 [Craft] => 0 [Dodge] => 0 [Empathy] => 0 [Enigma] => 0 [Etiquette] => 0 [Expression] => 0 [Finance] => 0 [Firearms] => 0 [Intimidation] => 0 [Investigation] => 0 [Larceny] => 0 [Law] => 0 [Leadership] => 0 [Linguistics] => 0 [Malkavian_Time] => 0 [Medicine] => 0 [Melee] => 0 [Occult] => 0 [Performance] => 0 [Politics] => 0 [Science] => 0 [Scrounge] => 0 [Security] => 0 [Stealth] => 0 [Streetwise] => 0 [Subterfuge] => 0 [Survival] => 0 [submit_skills] => Add Skills )

The array after filter:

Array ( [Academics] => 2 [Animal_Ken] => 3 [Athletics] => 2 )

Now I need to insert into skill_name = key, value = value for each array index.

Any ideas?

EDIT

After taking the advice I was given everything seems to be working correctly-ish.

Now I'm having the problem that any key that had a space in the name is now given an underscore by default.

e.g : Animal Ken --> Animal_Ken .. the database is rejecting the insert because of that.

Any way to strip out the underscore and leave it as a space again?

  • 写回答

3条回答 默认 最新

  • duanpu1064 2012-12-14 17:15
    关注

    Use a foreach and include the key.

    Example with a PDO parameterised query:

    $stmt = $db->prepare("INSERT INTO table(skill_name, value) VALUES(:skill_name,:value)");
    
    foreach($myArray as $key => $value)
    {
       // insert: $key = Academics, $value = 2
       $stmt->execute(array(':skill_name ' => $key, ':value' => $value));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码