【问题标题】:Object to Array Conversion giving weird result对象到数组的转换给出奇怪的结果
【发布时间】:2016-09-16 00:26:31
【问题描述】:

我正在尝试将类转换为数组。我正在使用以下代码:

class Abc{
    private $x, $y, $z;
    protected $x1, $y1, $z1;
    protected $x2, $y2, $z2;

    public function __construct() {
        $this->x=$this->y=$this->z=$this->x1=$this->y1=$this->z1=$this->x2=$this->y2=$this->z2=0;
    }

    public function getData() {
        return $x;
    }

    public function toArray() {
        return (array)$this;
    }
}
$abc = new Abc();
echo '<pre>', print_r($abc->toArray(), true), '</pre>';

现在奇怪的是输出:

Array
(
    [Propertyx] => 0
    [Propertyy] => 0
    [Propertyz] => 0
    [*x1] => 0
    [*y1] => 0
    [*z1] => 0
    [*x2] => 0
    [*y2] => 0
    [*z2] => 0
)

我想要没有 Class 名称且键名前没有 * 的干净键。

谁能建议我如何将成员名称转换为没有类名和没有 (*) 的数组键。也欢迎其他解决方案。

【问题讨论】:

  • 主要问题是print_r,由于OP在print_r中使用trueprint_r用数组显示信息。
  • print_r 将返回结果,而不是在您传递第二个参数 true 时将其发送到 std 输出,这就是我添加 true 的原因。

标签: php arrays object type-conversion


【解决方案1】:

有特殊功能

public function toArray() {
    return get_object_vars($this);
}

结果

<pre>Array
(
    [x] => 0
    [y] => 0
    [z] => 0
    [x1] => 0
    [y1] => 0
    [z1] => 0
    [x2] => 0
    [y2] => 0
    [z2] => 0
)
</pre>

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2013-08-20
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多