如何更改 Laravel 中数组的键? [重复]

问题描述 投票:0回答:1

上传 Excel 文件后,我得到下面给出的数组中的值

array:3 [▼ 
  0 => array:3 [▼
    "names" => "pa"
    "emails" => "[email protected]"
    "passwords" => 123456
  ]
  1 => array:3 [▼
    "names" => "a123"
    "emails" => "[email protected]"
    "passwords" => 123456
  ]
  2 => array:3 [▼
    "names" => "b123"
    "emails" => "[email protected]"
    "passwords" => 123456
  ]
]

如何将按键名称更改为姓名,将电子邮件更改为电子邮件?

php arrays mapping key laravel-9
1个回答
0
投票

您可以使用 array_map 函数来转换主数组中每个子数组的键

试试这个:

$originalArray = [
    [
        "names" => "pa",
        "emails" => "[email protected]",
        "passwords" => 123456
    ],
    [
        "names" => "a123",
        "emails" => "[email protected]",
        "passwords" => 123456
    ],
    [
        "names" => "b123",
        "emails" => "[email protected]",
        "passwords" => 123456
    ]
];

$newArray = array_map(function ($item) {
    return [
        'name' => $item['names'],
        'email' => $item['emails'],
        'password' => $item['passwords']
    ];
}, $originalArray);

print_r($newArray);

将会返回:

Array
(
    [0] => Array
        (
            [name] => pa
            [email] => [email protected]
            [password] => 123456
        )

    [1] => Array
        (
            [name] => a123
            [email] => [email protected]
            [password] => 123456
        )

    [2] => Array
        (
            [name] => b123
            [email] => [email protected]
            [password] => 123456
        )

)
© www.soinside.com 2019 - 2024. All rights reserved.