blitzkriegz
blitzkriegz

Reputation: 9576

Dynamically populate an associative array in PHP

I have an array with the following 6 strings.

user1 A
user2 B
user4 C
user2 D
user1 E

I need to create a Dictionary like:

arr['user1'] => ['A', 'E']
arr['user2'] => ['B', 'D']
arr['user4'] => ['C']

How to do this in PHP?

Upvotes: 5

Views: 13276

Answers (3)

Niklas Modess
Niklas Modess

Reputation: 2539

This is what you can do:

$strings = array(
    'user1 A',
    'user2 B',
    'user4 C',
    'user2 D',
    'user1 E',
);

$arr = array();

foreach ($strings as $string) {
    $values = explode(" ", $string);
    $arr[$values[0]][] = $values[1];
}

Upvotes: 3

Stegrex
Stegrex

Reputation: 4024

Try this, assuming $string is the string of values you have:

$mainArr = array();
$lines = explode("\n", $string);
foreach ($lines as $line) {
    $elements = explode(' ', $line);
    $mainArr[$elements[0]][] = $elements[1];
}
print_r($mainArr);

Assuming $mainArr is the array of values, and you already have the array:

$newArr = array(); // Declaring an empty array for what you'll eventually return.
foreach ($mainArr as $key => $val) { // Iterate through each element of the associative array you already have.
    $newArr[$key][] = $val; // Pop into the new array, retaining the key, but pushing the value into a second layer in the array.
}
print_r($newArr); // Print the whole array to check and see if this is what you want.

You'll want to look at multidimensional arrays in PHP: http://php.net/manual/en/language.types.array.php

Upvotes: 1

alex
alex

Reputation: 490143

This seems to work...

$arr = array();

foreach($lines as $line) {
    list($user, $letter) = explode(" ", $line);
    $arr[$user][] = $letter;
}

CodePad.

Upvotes: 6

Related Questions