用PHP计算对象

问题描述 投票:4回答:4

我正在使用PHP arraysobjects。我和他们一起工作已经有一段时间了。但是,我遇到了一个问题,可能有一个非常简单的解决方案。

我在一个函数中有一个变量$products,它在调用时接收值。我正在尝试计算变量中的对象以查看其中有多少产品。我尝试了简单的count($products)count((array)$products)功能,它无法正常工作。我知道这不是计算对象的最佳方式。

有没有办法统计它们?

object(stdClass)#46 (3) {
  ["0"]=>
  object(stdClass)#47 (1) {
    ["productid"]=>
    string(2) "15"
  }
  ["1"]=>
  object(stdClass)#48 (1) {
    ["productid"]=>
    string(2) "16"
  }
  ["2"]=>
  object(stdClass)#48 (1) {
    ["productid"]=>
    string(2) "26"
  }
}

我需要这个来返回3

object(stdClass)#20 (1) {
  ["productid"]=>
  string(2) "21"
}

我需要这个来返回1

php arrays count
4个回答
4
投票

计数功能是用于

数组从实现可数接口的类派生的对象stdClass都不是这些。完成你所追求的更简单/最快捷的方法是

$count = count(get_object_vars($products));

这使用PHP的get_object_vars函数,该函数将对象的属性作为数组返回。然后,您可以将此数组与PHP的count函数一起使用。


0
投票

你可以做类似的事情

count(get_object_vars($obj));

但是使用stdClass作为数组似乎有点奇怪。你为什么那样做?


0
投票

试试这个:$ count = sizeof(get_obj_vars($ products))

这里get_obj_vars函数将$products变量转换为数组,sizeof函数计算数组的大小并将其存储到变量$count


0
投票

从您的示例中,为此使用对象似乎是一种非常臃肿的方法。使用简单的数组会更容易,更快捷。

这个:

object(stdClass)#46 (3) {
    ["0"]=>
        object(stdClass)#47 (1) {
            ["productid"]=>
              string(2) "15"
    }
}

可能就是这样:

array(0 => 15);

甚至这个:

array(15);

您的示例似乎只是存储产品ID,因此您不必严格需要“productid”键

您需要使用对象的具体原因是什么?

© www.soinside.com 2019 - 2024. All rights reserved.