带有数字键的stdClass的array_push

时间:2018-01-30 02:44:56

标签: php stdclass array-push

我尝试使用类似于array_push的函数,但是在PHP中使用对象(stdClass)。看看我的期望:

<?php
$obj = new stdClass();
$obj->a = 'foo';
$obj->{'0'} = 'far';

var_dump($obj);
// > object(stdClass)#1 (2) { ["a"]=> string(3) "foo" ["0"]=> string(3) "far" }

var_dump(object_push($obj, 'coin'));
// > object(stdClass)#1 (3) { ["a"]=> string(3) "foo" ["0"]=> string(3) "far" ["1"]=> string(4) "coin" }

1 个答案:

答案 0 :(得分:0)

您可以使用此功能object_push

function object_push($object, $value) {
    $object->{max(array_filter(array_keys((array) $object), 'is_numeric') + [-1]) + 1} = $value;
    return $object;
}

然后使用它,就像使用array_push

一样
$obj = new stdClass();
$obj->a = 'foo';
$obj->{'0'} = 'far';

var_dump($obj);
// > object(stdClass)#1 (2) { ["a"]=> string(3) "foo" ["0"]=> string(3) "far" }

var_dump(object_push($obj, 'coin'));
// > object(stdClass)#1 (3) { ["a"]=> string(3) "foo" ["0"]=> string(3) "far" ["1"]=> string(4) "coin" }

和平