在循环中使用array_merge()合并数组的优化建议

<?php
$list1 = [['name' => '刘一'], ['name' => '陈二'], ['name' => '张三'],];
$list2 = [['name' => '李四'], ['name' => '王五'], ['name' => '赵六'],];
$list3 = [['name' => '孙七'], ['name' => '周八'], ['name' => '吴九'],];

$data = [];

for ($i = 1; $i <= 3; $i++) {
    // 在循环体內使用array_merge()合并数组非常耗资源,强烈建议不要使用这种方式
    $data = array_merge($data, ${"list{$i}"});
}

print_r($data);

<?php
$list1 = [['name' => '刘一'], ['name' => '陈二'], ['name' => '张三'],];
$list2 = [['name' => '李四'], ['name' => '王五'], ['name' => '赵六'],];
$list3 = [['name' => '孙七'], ['name' => '周八'], ['name' => '吴九'],];

$data = [];

for ($i = 1; $i <= 3; $i++) {
    // 把要合并的数组追加到变量中,在循环体外再执行合并数组操作
    $data[] = ${"list{$i}"};
}

$data = array_merge(...$data); // 注:$data前面加“...”是固定语法

print_r($data);

Copyright © 2024 码农人生. All Rights Reserved