skip to Main Content

I have an array like this

[
    123456 => 'John Doe'
    654321 => 'Doe John'
]

I want to change the array key (123456 and 654321) into an index (0,1,2,3,….,n) and save it into value, the expected result looks like this

array(
    0 => array(
        'name' => 'John Doe',
        'code' => 123456.
    ),
    1 => array(
        'name' => 'Doe John',
        'code' => 654321.
    ),
)

this is the code i have tried, i have only gotten so far

$thearray= array_map(function ($value, $key) {
                return $key;
            }, $thearray, array_keys($thearray));

2

Answers


  1. Use the foreach

    $pemeriksa = [
        123456 => 'John Doe',
        654321 => 'Doe John'
    ];
    
    $newArray = [];
    foreach ($pemeriksa as $key => $value) {
        $newArray[] = ["name" => $value , "code" => $key];
    }
    print_r($newArray);
    
    Login or Signup to reply.
  2. Within a foreach loop, define the keys and values using the keyname that you wish to see in the resultant rows, Then call compact() within the loops body before pushing the new row’s data into the result array.

    Code: (Demo)

    $result = [];
    foreach ($thearray as $code => $name) {
        $result[] = compact(['name', 'code']);
    }
    var_export($result);
    

    Your functional-style programming can be fixed up like this:

    Code: (Demo)

    var_export(
        array_map(
            fn($name, $code) => compact(['name', 'code']),
            $thearray,
            array_keys($thearray)
        )
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search