[英]php access property of object in array
I have a php variable that I got from a _POST. 我有一个从_POST获得的php变量。 var_dump shows this:
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" } }
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. 据我所记得
->age
是对象语法。 You need array syntax which would be ['age']
. 您需要使用
['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: 在此处了解更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.