0

I have this array:

$arr = array(
    0 => array( 'id' => 1, 'animal' => 'dog', 'color' => 'red' ),
    1 => array( 'id' => 12, 'animal' => 'cat', 'color' => 'green' ),
    2 => array( 'id' => 37, 'animal' => 'lion', 'color' => 'blue' ),
);

and I want this output:

$arr = array(
    1 => array( 'animal' => 'dog', 'color' => 'red' ),
    12 => array( 'animal' => 'cat', 'color' => 'green' ),
    37 => array( 'animal' => 'lion', 'color' => 'blue' ),
);

Any good idea instead of using php loops, etc ?
Any functions? like array_values or array_combine

=================
Possible solution

$new = array();
foreach( $arr as $item ){
    $id = array_shift( $item );
    $new[$id] = $item;
}
6
  • 3
    You're modifying an array. You're going to use a loop even if it's in a function call. Commented May 4, 2015 at 20:46
  • Looks like you're going to have to defend your aversion to using "PHP loops" and explain (in more detail) what you'd want to accomplish instead. Commented May 4, 2015 at 20:57
  • 1
    I think because the id is arbitrary, so there isn't going to be a function to do this. Everyone's brain just goes straight to the obvious...oh let's loop through that sucker! Then you're like...no loops please....and we're all like ...no. Commented May 4, 2015 at 21:04
  • You still haven't explained WHY you don't want to use loops. The consensus seems to be that this is the right time to use a loop, hence the downvotes. Commented May 4, 2015 at 21:05
  • 1
    @Arash it still actually uses loops (sure you don't see them- but so what), so i dont get it, no matter Commented May 4, 2015 at 22:50

2 Answers 2

6

Requires PHP >= 5.5.0 and the id will still be in the nested arrays:

$result = array_column($arr, null, 'id');
Sign up to request clarification or add additional context in comments.

Comments

2

One can define a new array and loop through the main array, using array_shift to pop first element (the id field) and then make the remaining part, value for that index in new array:

$new = array();
foreach( $arr as $item ){
    $id = array_shift( $item );
    $new[$id] = $item;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.