0

After uploading a excel file ,I get values in array given below

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
  ]
]

How can i change keys names as name, emails as email?

5
  • How did you get your array in the first place? Maybe change it there Commented Mar 20, 2023 at 9:35
  • I get it from excel. I cant excel. I have to change it in controller Commented Mar 20, 2023 at 9:37
  • What have you tried so far? Where are you stuck? foreaching over the array and changing the keys didn't work? Commented Mar 20, 2023 at 9:40
  • public function collection(Collection $rows) { dd($rows->toArray()); } . i have uploaded excel in laravel. Then i have to save in database. here i have to change keys Commented Mar 20, 2023 at 9:41
  • Topically relevant except dealing with prefixes instead of suffixes: Replace leading substring before a delimiter in all array keys Commented Dec 7, 2024 at 3:44

1 Answer 1

0

You can use the array_map function to transform the keys of each sub-array in your main array

Try this:

$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);

that will return :

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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.