1

I have simple array

array( 
   array( 'id'=>5, 'something' => 2, 'dsadsa' => 'fsfsd )
   array( 'id'=>20, 'something' => 2, 'dsadsa' => 'fsfsd )
   array( 'id'=>30, 'something' => 2, 'dsadsa' => 'fsfsd )
)

How to create associative array by id field (or something else) from it in the right way?

array( 
   '5' => array(  'something' => 2, 'dsadsa' => 'fsfsd )
   '20' => array(  'something' => 2, 'dsadsa' => 'fsfsd )
   '30' => array(  'something' => 2, 'dsadsa' => 'fsfsd )
)

2 Answers 2

2

Something along these lines.

$new_array = array();
foreach ($original_array as &$slice)
    {
    $id = (string) $slice['id'];
    unset($slice['id']);
    $new_array[$id] = $slice;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

I can do it with foreach, but I thought, that PHP have some specials functions for that task...
It's a pretty specific task, I don't think there's a built-in function for it.
This has a side effect of deleting the ['id'] elts from the original array, and because you don't unset $slice, any assignments to it will generate more side-effects in $new_array!
1

@NikitaKuhta, nope. There is no slice function which returns a column of values in a 2D keyed table associated with a given key or column heading. You can use some of the callback array_... functions, but you will still need to execute a custom function per element so its just not worth it. I don't like Core Xii's solution as this corrupts the original array as a side effect. I suggest that you don't use references here:

$new_array = array();
foreach ($original_array as $slice) {
    $id = (string) $slice['id'];
    unset($slice['id']);
    $new_array[$id] = $slice;
}
# And now you don't need the missing unset( $slice)

Comments

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.