Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

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.

share|improve this answer
 
Okay, now I'm convinced that foreach suits much better in such a situation. –  Serge Moonrider Jul 18 '12 at 7:36
add comment

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().

share|improve this answer
 
Nice one. Not sure it's really any better than a foreach though. ;) –  deceze Jul 18 '12 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 –  KingCrunch Jul 18 '12 at 7:36
add comment

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
)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.