Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用stdClass在数组中搜索?_Php - Fatal编程技术网

Php 如何使用stdClass在数组中搜索?

Php 如何使用stdClass在数组中搜索?,php,Php,我有一个包含stdClasses的数组: $a = new \stdClass(); $a->name = "aaa"; $a->type = "1"; $b = new \stdClass(); $b->name = "bbb"; $b->type = "2"; $c = new \stdClass(); $c->name = "ccc"; $c->type = "1"; $array = array($a, $b, $c); $count = 0;

我有一个包含stdClasses的数组:

$a = new \stdClass();
$a->name = "aaa";
$a->type = "1";

$b = new \stdClass();
$b->name = "bbb";
$b->type = "2";

$c = new \stdClass();
$c->name = "ccc";
$c->type = "1";

$array = array($a, $b, $c);

$count = 0;

foreach ($array as $arr) {
    if ($arr->type == 1) {
        $count++;
    }
}
计算值为1的类型的方法比计算foreach更好吗?我想计算很多值,这样foreach就不舒服了


可能是数组搜索或数组映射?

您可以使用数组过滤器

例如:

$a = new \stdClass();
$a->name = "aaa";
$a->type = "1";

$b = new \stdClass();
$b->name = "bbb";
$b->type = "2";

$c = new \stdClass();
$c->name = "ccc";
$c->type = "1";

$array = array($a, $b, $c);

$count = count(array_filter($array, function($d){
     return $d->type === "1";
}));

您可以使用数组过滤器

例如:

$a = new \stdClass();
$a->name = "aaa";
$a->type = "1";

$b = new \stdClass();
$b->name = "bbb";
$b->type = "2";

$c = new \stdClass();
$c->name = "ccc";
$c->type = "1";

$array = array($a, $b, $c);

$count = count(array_filter($array, function($d){
     return $d->type === "1";
}));

您所使用的是您的需求中最好的。您应该阅读它。您是否检查过foreach的实际速度慢?这听起来很像过早的优化。在代码中的某个地方,会有一个完整的数据迭代,移动该位只会隐藏事实,而不会阻止它。您使用的是您的需求中最好的。您应该阅读它,并且检查foreach是否确实很慢?这听起来很像过早的优化。在你的代码中的某个地方,会有一个完整的数据迭代,移动那个位,只会隐藏事实,而不会阻止它。你检查过这比简单的foreach快吗?是的,它们之间似乎没有太大的区别。当你问上面的问题时,我正在读这篇文章:在这里我找到了一些基准:你检查过这比简单的foreach快吗?是的,这两者之间似乎没有太大的区别。当你问上述问题时,我正在读这篇文章:在这里我找到了一些基准: