0
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?因为-and $符号在 mysql 中是有效的,但是当我尝试使用 foreach 显示它时,它就不起作用了。那么我应该怎么做才能在不编辑数据库表中的字段名称的情况下删除它?

4

3 回答 3

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] => 
)

我建议您创建更有效的变量名称而不是此类转换

于 2012-04-20T10:12:27.007 回答
1

像这样?

$cleaned = new stdClass();
foreach($obj as $key => $val) {
  $newKey = str_replace(array('$','-'), '', $key);
  $cleaned->$newKey = $val;
}
print_r($cleaned);
于 2012-04-20T10:06:52.353 回答
0

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

于 2012-04-20T10:16:41.273 回答