【问题标题】:Get an array from an object | php从对象中获取数组 | php
【发布时间】:2017-07-27 09:14:46
【问题描述】:

如何从对象中获取数组?我正在尝试访问空数组,以便验证它的空状态。

$object = Illuminate\Database\Eloquent\Collection Object;

print_r($object);

if(empty($object->array)){

}

输出

Illuminate\Database\Eloquent\Collection Object
(
    [items:protected] => Array
        (
        )

)

【问题讨论】:

  • 你可以对它进行类型转换,比如 (array)$array
  • @melkawakibi 看这里stackoverflow.com/a/4345609/2520628
  • 我更改了代码,现在它是一个 Eloquent 对象,里面有一个数组
  • 您是否尝试过 Gary Green 在此处 stackoverflow.com/questions/20563166/… 描述的不同方法?
  • @melkawakibi - 这是对象的 protected 属性..这意味着它不能从对象外部直接访问.. ..你为什么不直接使用对象方法来访问数据,而不是试图打破OOP

标签: php arrays laravel eloquent


【解决方案1】:

对象是 Eloquent\Collection 类型,这意味着它可以访问一组方法。

Eloquent\Collection | available methods

Collection 提供了一组方法来验证 Object 中数组的状态。其中两个在我描述的案例中很有趣(OP):

  • IsEmpty
  • IsNotEmpty

实施

$website = $this->websitedb->findOneByUrl($this->url);

if($website->isNotEmpty()){

    $uniqueId = rand() . $website[0]->id;

    //save scan to database
    $this->scan = $this->scandb->create($website[0]->id, $uniqueId);

    $this->scandb->createModule($this->scan->id, $options);

}

【讨论】:

    【解决方案2】:

    试试这样:

    if ($object->array === array()) {
        echo 'this is explicitly an empty array!';
    }
    

    【讨论】:

    • 它给出了这个错误,这个集合实例上不存在属性[数组]。
    猜你喜欢
    • 2019-06-05
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多