PHP如何引用字符串数组值 [英] PHP how to quote string array values

查看:149
本文介绍了PHP如何引用字符串数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下数组 $数组[0] =阵列(
    1=>酒吧,
    2=>富,
    3=> 13546
);
和我爆()的,则返回的值将是:吧,富,13546 不能在一个MySQL查询中使用......我怎样才能把单引号只是那些字符串值...

我已经tryed几个方法(如的foreach($数组$关键=> $值)与is_numeric检查()的$值,检查是确定的,但我不知道如何将值更改为$值'...)

对此有何toughts?

修改

我找到了另一种方式来为那些你们谁是有意这样做:

  $结果[0] =阵列(
    1=>酒吧,
    2=>富,
    3=> 1232.13
);$ copy_r = $结果[0];的foreach($ copy_r为$关键=> $值)
{
    如果(!is_numeric($值))
    {
        $ insert_array [] =`$ key` ='$价值';
    }
    其他
    {
        $ insert_array [] =`$ key` = $价值;
    }
}$ final_string =破灭(,,$ insert_array);
$ insert_q =INSERT INTO`table_name`设置$ final_string
             对重复密钥更新($ final_string);


解决方案

更好地使用prepared查询。但只是为了玩意儿:

 破灭('',array_map(函数($值){
    如果(!is_numeric($值)){
        返回''$价值。'';
        //添加双引号,但如果你preFER单引号,使用:
        //返回'。 $值。 ';
    }其他{
        返回$价值;
    }
} $数组[0]);

If I have the following array $array[0] = array( "1" => bar, "2" => foo, "3" => 13546 ); and I implode() it, the value that is returned will be: bar,foo,13546 which cannot be used in a mysql query... How can I place single quotes just to those values that are strings...

I've tryed a couple of ways (like foreach($array as $key=>$value) to check with is_numeric() the $value, and the check is ok but I dont know how to change the value to '$value'...)

Any toughts on this?

EDIT

I found another way to do this for those of you who are interested:

$result[0] = array(
    "1" => bar,
    "2" => foo,
    "3" => 1232.13
);

$copy_r = $result[0];

foreach($copy_r as $key=>$value)
{
    if(!is_numeric($value))
    {
        $insert_array[] = "`$key` = '$value'";
    }
    else
    {
        $insert_array[] = "`$key` = $value";
    }
}

$final_string = implode(',', $insert_array);
$insert_q = "INSERT INTO `table_name` SET $final_string
             ON DUPLICATE KEY UPDATE ($final_string)";

解决方案

Better use prepared queries. But just for funs sake:

implode(',', array_map(function($value) {
    if(!is_numeric($value)) {
        return '"' . $value . '"';
        //adds double quotes, but if you prefer single quotes, use:
        //return "'" . $value . "'";
    } else {
        return $value;
    }
}, $array[0]);

这篇关于PHP如何引用字符串数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆