【问题标题】:Remove index key from Array for accessing to object?从数组中删除索引键以访问对象?
【发布时间】:2011-11-29 13:56:00
【问题描述】:

如何从数组中删除索引键?

例如:

$getProduct = Product::find($product->ProductID);

数组结构看起来像这样:

Array
(
    [0] => Product Object
        (
            [id] => 26552
            [name] => Product Name One
        )

)

要获得name 的值,我必须这样做:

echo $getProduct[0]->name;

我想得到这样的值:

echo $getProduct->name;

【问题讨论】:

    标签: php arrays oop class


    【解决方案1】:

    要获得所需的值,您应该更改您的类“Product”,使其在调用 find 方法后返回您正在初始化的对象。

    【讨论】:

    • 在 Product 类中,它的获取是这样的:$statement->fetchAll(PDO::FETCH_CLASS, 'Product');
    【解决方案2】:
    $getProduct = $getProduct[0]; 
    

    将数组中的第一项放入它自己的变量中,然后您可以从中访问

    $getProduct->name
    

    但是,为了代码的可读性,我建议将其放入具有不同名称的变量中,也许:

    $product = $getProduct[0];
    echo $product->name;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-08
      • 2022-01-19
      • 1970-01-01
      • 2020-01-20
      • 2021-06-06
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多