使用foreach检索具有符号作为对象的数组值

时间:2013-12-27 11:31:46

标签: php foreach

我想检索数据库中的字段名称,其中一个名称为'wardno/houseno'。当我尝试使用foreach将其作为对象检索时,我正在

我的代码,

$this->db->select('*');
$this->db->from('tbl_application');
$this->db->where('app_no', '1/ML/201314/TVM');
$q=$this->db->get();
foreach($q->result() as $row) 
echo $row->wardno/houseno;

错误显示,

A PHP Error was encountered
Severity: Notice
Message: Undefined property: stdClass::$wardno
Filename: controllers/admin_sona.php
Line Number: 19

A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant houseno - assumed 'houseno'
Filename: controllers/admin_sona.php
Line Number: 19

A PHP Error was encountered
Severity: Warning
Message: Division by zero
Filename: controllers/admin_sona.php
Line Number: 19    

是否可以使用符号作为对象检索数据库值?

2 个答案:

答案 0 :(得分:1)

你可以试着给

foreach($q->result_array() as $row) 
  echo $row['wardno/houseno'];// or even echo $row['wardno\/houseno'];

而不是

foreach($q->result() as $row) 
  echo $row->wardno/houseno;

试一试!

---- EDIT ------

由于您不希望将其转换为数组,请尝试

echo $row[17]; //Just try. I am not sure where it hurts the code. In case of error, let me know in comments

答案 1 :(得分:0)

尝试改变这个:

$row->wardno

到此:

$row['wardno']

houseno也是如此

$row['houseno']

不知道你的数据库中是否有wardno/houseno,我认为你有两个不同的领域。如果是相同的字段,我建议您在数据库中使用_而不是/

如果是相同的字段,请尝试:

echo $row['wardno/houseno'];

将数组转换为对象试试这个:

function arrayToObject($array) {
    if (!is_array($array)) {
        return $array;
    }

    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
        foreach ($array as $name=>$value) {
            $name = strtolower(trim($name));
            if (!empty($name)) {
                $object->$name = arrayToObject($value);
            }
        }
        return $object;
    }
    else {
        return FALSE;
    }
}

$arr = arrayToObject($your_array);