How to access object of numeric indexed array in php
This question already has an answer here:
There is no way to implement like $k->0 or $k->'0' as you expected.
PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays. The key can either be an integer or a string. The value can be of any type. php array manual Take this interesting example,
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>
will output:
array(1) {
[1]=>
string(1) "d"
}
In your code, with this assign:
$cars['p'] = "Volvo";
$cars['q'] = "BMW";
$cars['r'] = "Toyota";
$cars['0'] = "Volvo";
$cars['1'] = "BMW";
$cars['2'] = "Toyota"
cars will be:
array(6) {
["p"]=>
string(5) "Volvo"
["q"]=>
string(3) "BMW"
["r"]=>
string(6) "Toyota"
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
and object k will be:
object(stdClass)#2 (6) {
["p"]=>
string(5) "Volvo"
["q"]=>
string(3) "BMW"
["r"]=>
string(6) "Toyota"
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
Use foreach() loop like:
foreach($cars as $car)
{
echo $car;
}
where $cars in an object.
foreach() reference
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
$cars['0'] = "Volvo";
$cars['1'] = "BMW";
$cars['2'] = "Toyota";
$k=(object)$cars;
foreach($k as $key) {
echo $key;
}
OR
$cars['0'] = "Volvo";
$cars['1'] = "BMW";
$cars['2'] = "Toyota";
foreach($cars as $key) {
echo $key;
}
链接地址: http://www.djcxy.com/p/64868.html
上一篇: 来自API调用的PHP对象数组
下一篇: 如何在php中访问数字索引数组的对象