Dynamically populate associative array in PHP

I have an array with the following 6 lines.

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 it in PHP?

+4
source share
3 answers

It seems to work ...

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

CodePad

+5
source

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]; } 
+3
source

Try this by assuming $ string is a string of values ​​that 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 an array of values, and you already have an 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 want to look at multidimensional arrays in PHP: http://php.net/manual/en/language.types.array.php

+1
source

Source: https://habr.com/ru/post/1437733/


All Articles