Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将对象转换为数组时删除(下划线)_Php_Arrays_Zend Framework_Naming Conventions - Fatal编程技术网

Php 将对象转换为数组时删除(下划线)

Php 将对象转换为数组时删除(下划线),php,arrays,zend-framework,naming-conventions,Php,Arrays,Zend Framework,Naming Conventions,根据Zend框架命名约定,私有变量应以z(下划线)开头。但在将对象转换为数组(强制转换)时会出现问题。数组元素键以“\”开头。如何在将对象转换为数组时删除下划线 比如说 class Book { private _name; private _price; } 将转换为 array('_name' => 'abc', '_price' => '100') 我想删除数组元素键中的“u”。没有确切的示例,这有点困难,但应该很接近。基本上是循环执行,查找以_开头的元

根据Zend框架命名约定,私有变量应以z(下划线)开头。但在将对象转换为数组(强制转换)时会出现问题。数组元素键以“\”开头。如何在将对象转换为数组时删除下划线

比如说

class Book {
     private _name;
     private _price;
}
将转换为

array('_name' => 'abc', '_price' => '100')

我想删除数组元素键中的“u”。

没有确切的示例,这有点困难,但应该很接近。基本上是循环执行,查找以_开头的元素,删除它们并向数组中插入一个无下划线的元素

$arr = array(
  'foo1' => 'bar1',
  '_foo2' => 'bar2',
  '_foo3' => 'bar3'
);

foreach ($arr as $key => $val) {
     if (substr($key,0,1) == '_') {
         unset($arr[$key]);
         $arr[substr($key,1)] = $val;
     }
}
在此之后,
$arr
将如下所示

Array
(
    [foo1] => bar1
    [foo2] => bar2
    [foo3] => bar3
)

我想也许你想要这样的东西:

//because of variable scope this method must be in the class where the private propeties are.
public function toArray() {
        $vars = get_object_vars($this);
        $array = array();
        foreach ($vars as $key => $value) {
            $array[ltrim($key, '_')] = $value;
        }
        return $array;
    }
这将允许您在模型、视图或控制器中调用
->toArray()