phparraysmappingkeylaravel-9

How can i change key of array in laravel?


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

array:3 [▼ 
  0 => array:3 [▼
    "names" => "pa"
    "emails" => "pa@gmail.com"
    "passwords" => 123456
  ]
  1 => array:3 [▼
    "names" => "a123"
    "emails" => "a123@gmail.com"
    "passwords" => 123456
  ]
  2 => array:3 [▼
    "names" => "b123"
    "emails" => "b123@gmail.com"
    "passwords" => 123456
  ]
]

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


Solution

  • 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" => "pa@gmail.com",
            "passwords" => 123456
        ],
        [
            "names" => "a123",
            "emails" => "a123@gmail.com",
            "passwords" => 123456
        ],
        [
            "names" => "b123",
            "emails" => "b123@gmail.com",
            "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] => pa@gmail.com
                [password] => 123456
            )
    
        [1] => Array
            (
                [name] => a123
                [email] => a123@gmail.com
                [password] => 123456
            )
    
        [2] => Array
            (
                [name] => b123
                [email] => b123@gmail.com
                [password] => 123456
            )
    
    )