PHP-数组组合无法正常工作


PHP- Array combine not working properly

我正在尝试进行数组组合,但它不能正常工作。我有一个名为$models的数组,它由对象组成,看起来像这样:

array:5 [▼
  0 => Comment {#377 ▶}
  1 => Thumb {#378 ▶}
  2 => View {#379 ▶}
  3 => Vote {#380 ▶}
]

然后,由于我将它传递给另一个函数,我又添加了一个对象作为元素,如下所示:

 array_push($models, new User);

然后我得到一个数组,看起来像这样:

 array:5 [▼
  0 => Comment {#377 ▶}
  1 => Thumb {#378 ▶}
  2 => View {#379 ▶}
  3 => Vote {#380 ▶}
  4 => User {#399 ▶}
]

然后我进行foreach循环,以在DB中获得每个模型的总计数,如下所示:

foreach ($models as $model){
  $modelCounts[] = $model->count();
}

我的$modelCounts看起来像这样:

array:5 [▼
  0 => 19
  1 => 22
  2 => 15
  3 => 17
  4 => 3
]

然后我尝试进行array_component,这样我的对象就是键,计数就是这样的值:

 $result = array_combine($models, $modelCounts);

但有些事情不正常,因为当我做dd($result);时,我得到:

  array:1 [▼
  "[]" => 3
]

但当我以另一种方式这样做时:

$result = array_combine($modelCounts, $models);

它运行良好,我得到:

array:5 [▼
  19 => Comment {#377 ▶}
  22 => Thumb {#378 ▶}
  15 => View {#379 ▶}
  17 => Vote {#380 ▶}
  3 => User {#399 ▶}
]

但我需要另一种方式,而不是这样。

对象不能用作关联数组的键,只允许使用标量值。

http://php.net/manual/en/language.types.array.php

数组和对象不能用作键。这样做将导致警告:偏移量类型非法。

第一个array_combine()失败的原因是objcet不能用作数组键。您可能想创建一个包含类名的数组,首先使用get_class()获取类名,然后将其与$modelCounts 组合

它应该是这样的

foreach ($models as $model){
  $modelNames[] = get_class($model);
}
$result = array_combine($modelNames, $modelCounts);