0

How do I go about reformatting an object?

Array
(
    [0] => Array
        (
            [user_id] => 5
            [first_name] => Ace
            [last_name] => Black
        )

    [1] => Array
        (
            [user_id] => 6
            [first_name] => Gary
            [last_name] => Surname
        )

    [2] => Array
        (
            [user_id] => 7
            [first_name] => Alan
            [last_name] => Person
        )

)

I need to reformat this so the user_id name is changed to just 'id' and the first_name and last_name values are merged into a single value called 'name' so the final result would look like:

Array
(
    [0] => Array
        (
            [id] => 5
            [name] => Ace Black
        )

)

2 Answers 2

3

You might find array_map useful for this

function fixelement($e)
{
    //build new element from old
    $n=array();
    $n['id']=$e['user_id'];
    $n['name']=$e['first_name'].' '.$e['last_name'];

    //return value will be placed into array
    return $n;
}

$reformatted = array_map("fixelement", $original);

As you can see, one downside is that this approach constructs a second copy of the array, but having written the callback, you can always use it 'in place' like this:

foreach($original as $key=>$value)
{
    $original[$key]=fixelement($value);
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to do it in place: Foreach that array, set the keys to the values you want, unset the keys for the values you no longer want.

If you want a copy of it: Foreach that array and ETL (extract, transform, load) into another similar array.

If you need further details to help let me know.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.