Build index array

From: Date: Sun, 19 Dec 2021 19:38:11 +0000
Subject: Build index array
Groups: php.general 
Request: Send a blank email to php-general+get-327866@lists.php.net to get a copy of this message
Hello, I'm looking for a PHP function that takes an array of objects (associative arrays) and changes the keys to one of the subvalues. You probably won't understand this, so I'll give an example. Here's the source data: [ [
    'col1' => 'val1a',
    'col2' => 'val2a',
    'col3' => 'val3a'
], [
    'col1' => 'val1b',
    'col2' => 'val2b',
    'col3' => 'val3b'
], [
    'col1' => 'val1c',
    'col2' => 'val2c',
    'col3' => 'val3c'
] ] The desired result for the index key 'col1' is: [ 'val1a' => [
    'col1' => 'val1a',
    'col2' => 'val2a',
    'col3' => 'val3a'
], 'val1b' => [
    'col1' => 'val1b',
    'col2' => 'val2b',
    'col3' => 'val3b'
], 'val1c' => [
    'col1' => 'val1c',
    'col2' => 'val2c',
    'col3' => 'val3c'
] ] All subarrays are still there (the order doesn't matter) but their keys are changed from 0, 1, 2... to the value of their 'col1' entry so I can access each subarray quickly and easily (and efficiently?) by its ID or name or whatever. That's similar to .NET LINQ's ToDictionary method that takes a key selector delegate and builds exactly this structure. It can be used to convert an ordinary database query result to a lookup dictionary. I know I can write this in a handful of lines of code, but I need this on a regular basis so before I roll my own version, I want to make sure I haven't missed something that's already there. Preferably for PHP 7.4 and newer. -Yves

« previous php.general (#327866) next »