Re: Build index array
| From: | Jigar Dhulla | Date: | Mon, 20 Dec 2021 07:54:35 +0000 |
| Subject: | Re: Build index array | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-327867@lists.php.net to get a copy of this message | ||
On Mon, Dec 20, 2021 at 1:08 AM Yves Goergen via php-general <
php-general@lists.php.net> wrote:
> 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
>
Hi Yves,
>> changes the keys to one of the subvalues
This is ambiguous, there is no ready function and you will have to write
one.
E.g.
function customFunction($array){
$output = [];
foreach($array as $i => $blob){
foreach($blob as $key => $value){
$output[$value] = $blob;
continue 2;
}
}
return $output;
}
$input = [
[
'col1' => 'val1a',
'col2' => 'val2a',
'col3' => 'val3a'
],
[
'col1' => 'val1b',
'col2' => 'val2b',
'col3' => 'val3b'
],
[
'col1' => 'val1c',
'col2' => 'val2c',
'col3' => 'val3c'
]
];
$output = customFunction($input);
echo json_encode($output);
=========
{
"val1a":{
"col1":"val1a",
"col2":"val2a",
"col3":"val3a"
},
"val1b":{
"col1":"val1b",
"col2":"val2b",
"col3":"val3b"
},
"val1c":{
"col1":"val1c",
"col2":"val2c",
"col3":"val3c"
}
}
--
- Jigar