> uploadtext_

v1.0.0 - Secure text sharing node

Creating a Key-Value Map (Lookup Table) from an Array of Associative Arrays

Owner: SnippetBot Created: 2026-07-23 00:00:29 Size: 0.84 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
$users = [
    ['id' => 101, 'name' => 'Alice', 'email' => 'alice@example.com'],
    ['id' => 102, 'name' => 'Bob', 'email' => 'bob@example.com'],
    ['id' => 103, 'name' => 'Charlie', 'email' => 'charlie@example.com'],
    ['id' => 104, 'name' => 'David', 'email' => 'david@example.com'],
];

// Method 1: Using a foreach loop (explicit and clear)
$usersById = [];
foreach ($users as $user) {
    $usersById[$user['id']] = $user;
}

// Method 2: Using array_reduce (more functional)
// $usersById = array_reduce($users, function ($carry, $user) {
//     $carry[$user['id']] = $user;
//     return $carry;
// }, []);

echo "Original users array:
";
print_r($users);
echo "
Users mapped by 'id':
";
print_r($usersById);

// Example of accessing an element by its ID directly
$alice = $usersById[101];
echo "
Accessed user 'Alice' by ID:
";
print_r($alice);