PHP在对象数组中创建和访问属性

时间:2016-05-11 15:24:06

标签: php arrays

我已经看到很多类似问题的答案,但没有一个我能用有限的PHP排序解析。简单地说,我想创建一个快速的对象列表,然后遍历该数组并访问每个对象的属性。在javascript中它非常简单:

$array_of_objects = array();
$object = new stdClass();
$object->color = 'red';
$object->size = 10;
array_push($array_of_objects, $object);
$object2 = new stdClass();
$object2->color = 'green';
$object2->size = 4;
array_push($array_of_objects, $object2);

我正在使用PHP 5.3,这是我对它的第一次丑陋的抨击:

protected function verifyLoggedUser( $module, $action ) {
        $result = false;
        //logical to validate user permissions
        if( !$result )
            return $this->filter('before', 'profileValidate');
        else
            return $result;
}

这看起来很可怕。

4 个答案:

答案 0 :(得分:1)

<?php
$arrayOfObjects = array(
    (object)array('color' => 'red', 'size' => 10),
    (object)array('color' => 'blue', 'size' => 4),
    (object)array('color' => 'green', 'size' => 6),
);


foreach($arrayOfObjects as $obj) {
    echo $obj->color;
    echo $obj->size;
}

PHP数组也可以有字符串索引。这会不会满足您的需求?

<?php
$arrayOfObjects = array(
    array('color' => 'red', 'size' => 10),
    array('color' => 'blue', 'size' => 4),
    array('color' => 'green', 'size' => 6),
);


foreach($arrayOfObjects as $obj) {
    echo $obj['color'];
    echo $obj['size'];
}

答案 1 :(得分:1)

JSON几乎就像JavaScript声明。只需确保使用双引号"

$array_of_objects = json_decode('[
{"color": "red", "size": 10},
{"color": "blue", "size": 4},
{"color": "green", "size": 6}
]');

foreach($array_of_objects as $obj) {
    echo $obj->color;
    echo $obj->size;
}

答案 2 :(得分:0)

如何创建一个具有两个属性$ color和$ Size的类? 实例化一个对象并将其推送到一个数组; 试试这个:

<?php

$Array = array();
$YourObject = new YourClass();
$YourObject->color = "red";
$YourObject->size = "10";

array_push($Array, $YourObject);


$YourObject = new YourClass();
$YourObject->color = "blue";
$YourObject->size = "4";

array_push($Array, $YourObject);


$YourObject = new YourClass();
$YourObject->color = "green";
$YourObject->size = "6";

array_push($Array, $YourObject);

print "<pre>";
print_r($Array);
print "</pre>";


class YourClass {
    public $color;
    public $size;
}
?>

答案 3 :(得分:0)

使用foreach循环遍历数组并显示其成员对象的属性。

以下是参考资料:

所以你的代码应该是这样的:

$array_of_objects = array();
$object = new stdClass();
$object->color = 'red';
$object->size = 10;
array_push($array_of_objects, $object);
$object2 = new stdClass();
$object2->color = 'green';
$object2->size = 4;
array_push($array_of_objects, $object2);

foreach($array_of_objects as $object){
    echo "Color: " . $object->color . ", Size: " . $object->size . "<br />";
}

<强>输出:

Color: red, Size: 10
Color: green, Size: 4

旁注:您可以var_dump($array_of_objects);查看完整的数组结构。