如何在php中访问数字索引数组的对象
这个问题在这里已经有了答案:
无法按照您的预期实现$ k-> 0或$ k - >'0'。
PHP数组可以同时包含整数和字符串键,因为PHP不区分索引数组和关联数组。 密钥可以是整数或字符串。 该值可以是任何类型。 php数组手册以这个有趣的例子,
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>
会输出:
array(1) {
[1]=>
string(1) "d"
}
在您的代码中,使用此分配:
$cars['p'] = "Volvo";
$cars['q'] = "BMW";
$cars['r'] = "Toyota";
$cars['0'] = "Volvo";
$cars['1'] = "BMW";
$cars['2'] = "Toyota"
汽车将是:
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"
}
而对象k将是:
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"
}
使用foreach()循环,如:
foreach($cars as $car)
{
echo $car;
}
$汽车在一个物体中。
foreach()引用
foreach循环仅对数组起作用,并用于遍历数组中的每个键/值对。
$cars['0'] = "Volvo";
$cars['1'] = "BMW";
$cars['2'] = "Toyota";
$k=(object)$cars;
foreach($k as $key) {
echo $key;
}
要么
$cars['0'] = "Volvo";
$cars['1'] = "BMW";
$cars['2'] = "Toyota";
foreach($cars as $key) {
echo $key;
}
链接地址: http://www.djcxy.com/p/64867.html