开发者

Reformat a simple PHP array

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] => 开发者_如何学CSurname
        )

    [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
        )

)


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜