简体   繁体   中英

PHP: how to create associative array by key?

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

Something along these lines.

$new_array = array();
foreach ($original_array as &$slice)
    {
    $id = (string) $slice['id'];
    unset($slice['id']);
    $new_array[$id] = $slice;
    }

@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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM