首页 > 解决方案 > 什么更好?在foreach中调用函数还是在函数中调用foreach?

问题描述

我正在尝试改进我的代码,现在我想知道什么更好(性能和代码风格):

public function xxx() {
    ...
    foreach ($customers as $customer) {
        $this->createCustomer($customer);
    }
    ...
}

public function createCustomer($customer) {
    // Create customer
}

或者

public function xxx() {
    ...
    $this->createCustomers($customers);
    ...
}

public function createCustomers($customers) {
    foreach ($customers as $customer) {
        // Create customer
    }
}

谢谢!

标签: phplaravelfunctiongenericsforeach

解决方案


这里有更好的版本

public function xxx() {
    ...
    $ToBeCreatedCustomers = validateAndFormatCustomers($customers)
    Customer::insert($ToBeCreatedCustomers);
    ...
}

public function validateAndFormatCustomers() {
    $ToBeCreatedCustomers = []
    foreach ($customers as $customer) {
        $ToBeCreatedCustomers[] = [
            'name' => $customer['name'],
            .....
        ]
    }
    return $ToBeCreatedCustomers;
}

推荐阅读