在名称中显示带有特殊字符“$”或“ - ”的变量

时间:2012-04-20 10:03:48

标签: php mysql xml ascii utf

stdClass Object
(
    [campaign-ID] => 1
    [campaign_name] => Sample Campaign
    [start_duration] => 2012-04-17
    [end_duration] => 2012-04-17
    [activity$] => 
    [survey_settings] => Ordering K-Cup Packs
    [$limit] => sample
    [$goal] => 
)

如何删除 - 和$?使用PHP? 因为-$符号在mysql中有效,但是当我尝试使用foreach显示它时,它不会起作用。那么如何在不编辑数据库表中的字段名的情况下删除它呢?

3 个答案:

答案 0 :(得分:2)

我不确定你在哪里上课但是这里有很多无效的命名

示例

$goal campaign-ID等。

我必须重建你的课程,它看起来像这样

$st= new stdClass();
$st->{"campaign-ID"} = 1 ;
$st->campaign_name = "Sample Campaign" ;
$st->start_duration = "2012-04-17" ;
$st->start_duration = "2012-04-17" ;
$st->{'activity$'} = null ;
$st->survey_settings = "Ordering K-Cup Packs" ;
$st->{'$limit'}  = "sample" ;
$st->{'$goal'} = null ;


$std = new stdClass();
foreach($st as $key => $value)
{
    $key = str_replace(array('$',"-"),array('',"_"),$key);
    $std->{$key} = $value ;
}

echo "<pre>" ;
print_r($std);

输出

stdClass Object
(
    [campaign_ID] => 1
    [campaign_name] => Sample Campaign
    [start_duration] => 2012-04-17
    [activity] => 
    [survey_settings] => Ordering K-Cup Packs
    [limit] => sample
    [goal] => 
)

我建议你创建更多有效的变量名称,而不是这样的转换

答案 1 :(得分:1)

喜欢这个吗?

$cleaned = new stdClass();
foreach($obj as $key => $val) {
  $newKey = str_replace(array('$','-'), '', $key);
  $cleaned->$newKey = $val;
}
print_r($cleaned);

答案 2 :(得分:0)

删除无效的PHP字符与rm * .php一样简单。