5

我有一个包含以下 6 个字符串的数组。

user1 A
user2 B
user4 C
user2 D
user1 E

我需要创建一个字典,如:

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

如何在 PHP 中做到这一点?

4

3 回答 3

6

这似乎工作......

$arr = array();

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

键盘

于 2012-10-04T06:49:02.697 回答
3

这是你可以做的:

$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];
}
于 2012-10-04T06:51:53.740 回答
1

试试这个,假设 $string 是你拥有的值的字符串:

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

假设 $mainArr 是值数组,并且您已经拥有该数组:

$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.

您需要查看 PHP 中的多维数组:http: //php.net/manual/en/language.types.array.php

于 2012-10-04T06:49:01.833 回答