简体   繁体   中英

php access property of object in array

I have a php variable that I got from a _POST. var_dump shows this:

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" } }

I loop through the array but can't get the properties to print:

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

age and amount are blank:

age=, amount=

As far as I remember ->age is object syntax. You need array syntax which would be ['age'] .

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

There's a difference between associative arrays and objects.

$incomeSched[$i]->age;

is what you'd do to access the property of an object. For an associative array you'd want

$incomeSched[$i]["age"]

You can cast an array as an object if need be:

$obj = (object)$incomeSched;

learn more here:

PHP - associative array as an object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM