3

I have the following multidimensional array:

$userList = array(
    0 => array('id' => 1000, 'first_name' => 'John', 'last_name' => 'Smith'),
    1 => array('id' => 1001, 'first_name' => 'Sam', 'last_name' => 'Johnson'),
);

I want to convert it to the array like:

$userData = array(
    1000 => 'John Smith',
    1001 => 'Sam Johnson',
);

It's quite obvious for me how to implement this using foreach loop, but I wonder if it's possible to do this with PHP array functions like array_map or array_walk. Please use PHP 5.3 for the callback function. Thank you!

3 Answers 3

5

Since those functions only work on the array values, getting them to set the key in the new array is somewhat awkward. One way to do it is:

$arr = array_combine(
    array_map(function ($i) { return $i['id']; }, $arr),
    array_map(function ($i) { return "$i[first_name] $i[last_name]"; }, $arr)
);

This is a case where a foreach is much more appropriate.

1
  • Okay, now I'm convinced that foreach suits much better in such a situation. Commented Jul 18, 2012 at 7:36
1

A minor trick from the functional programming.

$arr = array_reduce(
  $arr,
  function ($result, $item) {
    $result[$item['id']] = $item['first_name'] . ' ' . $item['last_name'];
    return $result;
  },
  array()
);

See array_reduce().

2
  • Nice one. Not sure it's really any better than a foreach though. ;) Commented Jul 18, 2012 at 7:29
  • I usually use 4 spaces for intendation, what makes it slightly better readable. Also I would use objects instead, what would result in something like return array_merge($result,array($user->id => $user->getFullname()); as callback. However: Don't know either :D Commented Jul 18, 2012 at 7:36
0

Code:

<?php

function convertArray ( $array ) {

    $newUserList = array();
    foreach ( $array as $value ) {
        $newUserList[ $value[ 'id' ] ] = $value[ 'first_name' ] . ' ' . $value[ 'last_name' ];
    }

    return $newUserList;

}   

$userList = array(
    0 => array( 'id' => 1000, 'first_name' => 'John', 'last_name' => 'Smith' ),
    1 => array( 'id' => 1001, 'first_name' => 'Sam', 'last_name' => 'Johnson' )
);

$newUserList = convertArray( $userList );

?>

Output:

Array
(
    [1000] => John Smith
    [1001] => Sam Johnson
)

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.