从多个 post 对象字段中获取总数

Get total number from multiple post object fields

我是 PHP 的新手,所以我的问题可能有一个非常简单的答案,但我搜索了 ACF 论坛和 Google 但没有找到答案。希望这里有人可以提供帮助。

我的页面上有四个多 select post 对象字段,我正在尝试获取 post 的总数(或者在我的案例中是工作人员)那些 post 对象。我想以某种方式将它们组合起来,以便我可以将总数与条件一起使用。

我可以使用 count().

获取单个 post 对象的数量
$instructor = get_field('course_instructors');

if (count($instructors) > 1) {
  // dosomething...
}

但是尝试在 count() 内将它们加在一起是行不通的。

$instructor = get_field('course_instructors');
$leaders = get_field('course_leaders');
$designers = get_field('course_designers');
$speakers = get_field('course_speakers');

if (count($instructors + $leaders + $designers + $speakers) > 1) {
  // dosomething...
}

我也尝试过 array_merge() 和其他数组函数,但没有成功,但我不能 100% 确定 post 对象的输出是一个数组...虽然它当我使用 print_r().

时看起来像

理想情况下,我的代码会像这样工作:

$instructor = get_field('course_instructors');
$leaders = get_field('course_leaders');
$designers = get_field('course_designers');
$speakers = get_field('course_speakers');
$all_staff = $instructors + $leaders + $designers + $speakers;

if (count($all_staff) > 1) {
  // dosomething...
}

当我这样做时,出现错误:"Fatal error: Unsupported operand types in..."。

希望有人能为我回答这个问题,或者至少指出正确的方向。 提前致谢。非常感谢!

你走的很好,但是 PHP 的 count 一次只接受一个混合 object/array,所以你应该选择:

if ( count($instructors) + count($leaders) + count($designers) + count($speakers) > 1) {
    // dosomething...
}

或者您可以将结果保存在一个变量中,以防您稍后需要在您的代码中重用它:

$count = count($instructors) + count($leaders) + count($designers) + count($speakers);

if ( $count > 1 ) {
     // dosomething...
}

希望对您有所帮助!

这是最终对我有用的解决方案:
(基于 John Huebner 在 my post on the ACF support forum 上提供的建议。)

$instructors_total = 0;
$instructors = get_field('instructors');
if (is_array($instructors)) {
  $instructors_total = count($instructors);
}

$leaders_total = 0;
$leaders = get_field('leaders');
if (is_array($leaders)) {
  $leaders_total = count($leaders);
}

$designers_total = 0;
$designers = get_field('designers');
if (is_array($designers)) {
  $designers_total = count($designers);
}

$speakers_total = 0;
$speakers = get_field('speakers');
if (is_array($speakers)) {
  $speakers_total = count($speakers);
}

$staff_total = $instructors_total + $leaders_total + $designers_total + $speakers_total;

如上所述,这是基于@hube2 的两个建议,除了我在我的 is_array() 验证中使用 count() 而不是在它们之外。使用 count() 在验证之外将总数相加会返回“1”,即使数组为空也是如此。所以如果我所有的数组都是空的,我仍然得到“4”。 count() 文档指出:"If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned."

可能有更好的方法来执行此操作,但这对我来说效果很好。

感谢您的帮助!