检查 stdClass 对象在 PHP 中是否有“条目”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4527963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:19:51  来源:igfitidea点击:

Check if a stdClass object has "entries" in PHP

php

提问by ipalaus

I have a model that checks for entries en a database. Like this:

我有一个模型可以检查数据库中的条目。像这样:

public function getByID($id)
{
    if(false == is_numeric($id))
        return false;

    $images = array();

    $query = $this->db->where("id_album", $id)->order_by("order", "ASC")->get("images");

    foreach($query->result() as $row)
        $images[] = $row;

    return (object) $images;
}

In my view I want to know if I have a rows or not, to show the images or not. I do this:

在我看来,我想知道我是否有一行,以显示图像。我这样做:

<?php if(false != isset($content->images)): ?>
    <pre><?php print_r($content->images); ?></pre>
<?php endif; ?>

But every time I try to skip when I've no results (i get a stdClass() empty) I fail. I tried isset, $content->images != NULL, !$content->images... I don't know how to do it to skip the "Severity: Notice Message: Undefined variable".

但是每次当我没有结果时尝试跳过(我得到一个空的 stdClass())我失败了。我试过isset$content->images != NULL!$content->images...我不知道该怎么做,以跳过“严重性:通知消息:未定义的变量”。

Thank you in advance.

先感谢您。

UPDATE:

更新:

$contenthas more sets than images, like $content->_dataor $content->title.

$content具有比图像更多的集合,例如$content->_data$content->title

When I've NO images on database and i've no return from MySQL, doing this:

当我在数据库上没有图像并且我没有从 MySQL 返回时,执行以下操作:

<?php echo count($content->images); ?>
<pre><?php print_r($content->images); ?></pre>

The output is:

输出是:

1
stdClass ( )

回答by RobertPitt

why cant you just use

为什么你不能使用

if(isset($content->images)) //Isset also will make sure $content is set
{

}

This way your performing checks on both entities.

这样您就可以对两个实体进行检查。

As images is an object that can be iterated you can also check that.

由于图像是可以迭代的对象,因此您也可以检查它。

if(isset($content->images) && is_object($content->images))
{

}

Also you seem to be using the wrong comparison operators for boolean's, you should be using the strict standards for comparison, which is ===and not ==, or !==and not !=:)

此外,您似乎对布尔值使用了错误的比较运算符,您应该使用严格的比较标准,即===and not==!==not !=:)

Merry Christmas

圣诞节快乐

回答by lucifurious

I know this is an old question but it still hasn't been answered properly.

我知道这是一个老问题,但仍然没有得到正确回答。

issetonlytests if a key exists andnot if it is null. This is an important distinction. See the examples: http://us1.php.net/isset

isset测试键是否存在而不测试它是否为空。这是一个重要的区别。查看示例:http: //us1.php.net/isset

To properly test if an array contains a key, array_key_existsshould be used as stated elsewhere on this page.

要正确测试数组是否包含键,array_key_exists应按照本页其他地方的说明使用。

On the other hand, to test if an object contains a property, the property_existsmethod should be used. property_exists()returns TRUEeven if the property has a NULLvalue.

另一方面,要测试对象是否包含属性,property_exists应该使用该方法。即使该属性具有值也property_exists()返回。TRUENULL

So, your code should look like this (yeah, I changed it a bit but the point remains the same):

因此,您的代码应如下所示(是的,我对其进行了一些更改,但要点保持不变):

<?php
    if ( isset( $content ) && property_exists( $content, 'images' ) ) {
        echo '<pre>' . print_r( $content->images, true ) . '</pre>';
    }
?>

回答by Damien Overeem

Ran into this question/answers while trying to find out how to check for an empty stdClass.

在尝试找出如何检查空 stdClass 时遇到了这个问题/答案。

The given answers are not really answers to the question in the topic, leading people here that wont get a clear answer, so I'll add an improved version:

给出的答案并不是主题中问题的真正答案,导致这里的人不会得到明确的答案,因此我将添加一个改进版本:

Question:Check if a stdClass object has “entries” in PHP

问题:检查一个 stdClass 对象在 PHP 中是否有“条目”

Answer:

回答:

Typecast the stdClass to array, see below:

将 stdClass 类型转换为数组,见下文:

$someObject = new StdClass();
var_dump(empty($someObject)); // Will return false, because $someObject is an stdClass

// Convert to array
$someObjectArr = (array)$someObject;
var_dump(empty($someObjectArray)); // Will return true

回答by Jacob Relkin

Use countwith isset:

使用countisset

if(isset($content) && count($content)) {
  //$content has properties...
  if(isset($content->images)) { //$content->images exists
    //awesome stuff goes here...
  }  
}

codepad example

键盘示例

回答by ironchicken

I wanted to check if some object has allof the given properties. So I did this:

我想检查某个对象是否具有所有给定的属性。所以我这样做了:

function hasAllProperties($object, array $properties) {
    return array_reduce(
        $properties,
        function ($acc, $property) use ($object) {
            return $acc && property_exists($object, $property);
        },
        true
    );
};

$someObject = json_decode('{"foo": "bar", "baz": "quux"}');

echo 'should be true ' . (hasAllProperties($someObject, ['foo', 'baz']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAllProperties($someObject, ['foo', 'baz', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAllProperties($someObject, ['foo', 'moo']) ? 'TRUE' : 'FALSE') . "\n";

Then in addition you may also want to check if just one or more of the properties exists:

此外,您可能还想检查是否仅存在一个或多个属性:

function hasAnyProperties($object, array $properties) {
    return array_reduce(
        $properties,
        function ($acc, $property) use ($object) {
            return $acc || property_exists($object, $property);
        },
        false
    );
};

$someObject = json_decode('{"foo": "bar", "baz": "quux"}');

echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'baz']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'baz', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAnyProperties($someObject, ['moo']) ? 'TRUE' : 'FALSE') . "\n";

回答by CyrilRegal

If i want to test the whole object to know if i do something or not i proced like that:

如果我想测试整个对象以了解我是否做了某事,我会这样做:

if($object != new stdClass())
{
    // do something
}