【问题标题】:php access property of object in arrayphp访问数组中对象的属性
【发布时间】:2018-11-12 16:54:13
【问题描述】:

我有一个从 _POST 获得的 php 变量。 var_dump 显示:

array(9) { [0]=> array(2) { ["age"]=> string(2) "62"
["amount"]=> string(5) "10878" } [1]=> array(2) { ["age"]=> string(2) "63"
["amount"]=> string(5) "10878" } [2]=> array(2) { ["age"]=> string(2) "64"
["amount"]=> string(5) "10878" } [3]=> array(2) { ["age"]=> string(2) "65"
["amount"]=> string(5) "10878" } [4]=> array(2) { ["age"]=> string(2) "66"
["amount"]=> string(5) "10878" } [5]=> array(2) { ["age"]=> string(2) "67"
["amount"]=> string(5) "28416" } [6]=> array(2) { ["age"]=> string(2) "68" 
["amount"]=> string(5) "28416" } [7]=> array(2) { ["age"]=> string(2) "69" 
["amount"]=> string(5) "28416" } [8]=> array(2) { ["age"]=> string(2) "70" 
["amount"]=> string(5) "28416" } }

我循环遍历数组但无法获取要打印的属性:

for ($i=0; $i<count($incomeSched); $i++) {
    $age = $incomeSched[$i]->age;
    $amt = $incomeSched[$i]->amount;
    echo "age=$age, amount=$amt<br>";
}

年龄和金额为空:

age=, amount=

【问题讨论】:

  • 目前在移动设备上,但您是否尝试过 $incomeSched[$i]['age']?
  • 是的,这行得通。谢谢!

标签: php arrays


【解决方案1】:

关联数组和对象是有区别的。

$incomeSched[$i]->age;

是您访问对象属性的方法。对于您想要的关联数组

$incomeSched[$i]["age"]

如果需要,您可以将数组转换为对象:

$obj = (object)$incomeSched;

在这里了解更多:

PHP - associative array as an object

【讨论】:

    【解决方案2】:

    据我所知-&gt;age 是对象语法。您需要数组语法,即['age']

    for ($i=0; $i<count($incomeSched); $i++) {
        $age = $incomeSched[$i]['age'];
        $amt = $incomeSched[$i]['amount'];
        echo "age=$age, amount=$amt<br>";
    }
    

    【讨论】:

    • 谢谢。您是对的,但@Michael Beeson 也是如此,他提供了更多信息以帮助其他人搜索此内容,因此我将答案归功于他。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2016-10-28
    • 2011-03-09
    • 1970-01-01
    相关资源
    最近更新 更多