PHP:修剪对象中的每个元素,如果为空,则设置为 N/A

发布于 2024-09-13 00:49:59 字数 461 浏览 5 评论 0原文

我有一个对象:

stdClass Object
(
    [Color] => Red
    [Shape] => Round
    [Taste] => Sweet
)

我想修剪对象中的每个元素,如果该元素为空,则将其设置为“N/A”

所以这个对象:

stdClass Object
(
    [Color] => Red
    [Shape] => 
    [Taste] => Sweet
)

将变成这样:

stdClass Object
(
    [Color] => Red
    [Shape] => N/A
    [Taste] => Sweet
)

我应该如何完成这个,也许是 array_walk?

I have an object:

stdClass Object
(
    [Color] => Red
    [Shape] => Round
    [Taste] => Sweet
)

I want to trim each of the elements in the object and if that element is empty, set it to 'N/A'

So this object:

stdClass Object
(
    [Color] => Red
    [Shape] => 
    [Taste] => Sweet
)

Would become this:

stdClass Object
(
    [Color] => Red
    [Shape] => N/A
    [Taste] => Sweet
)

How should I accomplish this, array_walk maybe?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小梨窩很甜 2024-09-20 00:49:59

让我们保持简单:

$foo = new StdClass;
$foo->prop1 = '   foo   ';
$foo->prop2 = NULL;
$foo->prop3 = 'bar';

foreach($foo as &$prop) {
    $prop = trim($prop);
    if (empty($prop)) {
        $prop = 'N/A';
    }
}

print_r($foo);

这将给出:

stdClass Object
(
    [prop1] => foo
    [prop2] => N/A
    [prop3] => bar
)

Let's keep it simple:

$foo = new StdClass;
$foo->prop1 = '   foo   ';
$foo->prop2 = NULL;
$foo->prop3 = 'bar';

foreach($foo as &$prop) {
    $prop = trim($prop);
    if (empty($prop)) {
        $prop = 'N/A';
    }
}

print_r($foo);

And that would give:

stdClass Object
(
    [prop1] => foo
    [prop2] => N/A
    [prop3] => bar
)
孤独岁月 2024-09-20 00:49:59

这是一个更复杂(且速度更慢)的方法,它允许您迭代对象的所有属性,而不管可见性如何。这需要 PHP5.3:

function object_walk($object, $callback) {

    $reflector = new ReflectionObject($object);
    foreach($reflector->getProperties() as $prop) {
        $prop->setAccessible(TRUE);
        $prop->setValue($object, call_user_func_array(
            $callback, array($prop->getValue($object))));
    }
    return $object;
}

但是如果所有对象属性都是公共的,则无需使用它。

Here is a more sophisticated (and slower) one that would allow you to iterate over all properties of an object, regardless of Visibility. This requires PHP5.3:

function object_walk($object, $callback) {

    $reflector = new ReflectionObject($object);
    foreach($reflector->getProperties() as $prop) {
        $prop->setAccessible(TRUE);
        $prop->setValue($object, call_user_func_array(
            $callback, array($prop->getValue($object))));
    }
    return $object;
}

But there is no need to use this if all your object properties are public.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文