Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array whose values are all arrays of a specific format that looks like this:

Array
(
    [0] => Array
           (
               [username] => John
           )    
    [1] => Array
           (
               [username] => Joe
           )
    [2] => Array
           (
               [username] => Jake
           )
)

and I would like to have this:

Array
(
    [0] => John   
    [1] => Joe
    [2] => Jake
)

I can do this manually with a loop but is there a better way? If not, is it possible to do this for an array of objects that have a common attribute?

share|improve this question
add comment (requires an account with 50 reputation)

4 Answers

up vote 10 down vote accepted

why complicate things?

foreach($array as $k=>$v) {
    $new[$k] = $v['username'];
}
share|improve this answer
+1 for using a simplified solution for an especific problem. – Luiz Damim Feb 18 '10 at 15:06
add comment (requires an account with 50 reputation)

If you're using PHP 5.3 you can make use of array_walk_recursive and a closure (the closure can be replaced by a normal function if your PHP version < 5.3):

function arrayFlatten(array $array) {
    $flatten = array();
    array_walk_recursive($array, function($value) use(&$flatten) {
        $flatten[] = $value;
    });

    return $flatten;
}

$nested = array(
    array('username' => 'John'),
    array('username' => 'Joe'),
    array('username' => 'Jake'),
);

$flattened = arrayFlatten($nested);

var_dump($flattened)

array
  0 => string 'John' (length=4)
  1 => string 'Joe' (length=3)
  2 => string 'Jake' (length=4)
share|improve this answer
add comment (requires an account with 50 reputation)
$new = array_map(create_function('$auser', 'return $auser["username"];'), $array);

If using objects you could just change return $auser["username"]; to return $auser->get_username();

share|improve this answer
add comment (requires an account with 50 reputation)

Try this code:

foreach   ($arr as $key => $val)
{
    sort($val );
    $new = array_merge($val, $new);
}
print_r ($new);
share|improve this answer
add comment (requires an account with 50 reputation)

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.