donglang1894
2019-06-14 10:44
浏览 97
已采纳

PHP - 在内置函数中使用另一个数组中的特定元素填充数组

I have a list of objects ( Cars ) so cars[0]->getId() is 12, cars[1]->getId is 25 etc. I want to fill an array with these IDs without using foreach

Currently I am doing it like this:

$carIds = array()
foreach ($cars as $car) {
   $carIds[] = $car->getId();
}

Is there an in built function to directly populate the array?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doubeishuai6598 2019-06-14 10:47
    已采纳

    Use https://www.php.net/manual/en/function.array-map.php Sample code:

    $result = array_map(function ($car) {
      return $car->getId();
    }, $cars);
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题