Enter two PHP arrays randomly?

Single array

Array ( [0] => love [1] => home [2] => google [3] => money ) 

And further

 Array ( [0] => 111 [1] => 222 [2] => 333 [3] => 444 [4] => 555 [5] => 666 [6] => 777 [7] => 888 ) 

I want to make a 3rd array that looks like this:

 Array ( [love] => 111 [google] => 222 [home] => 333 [love] => 444 [google] => 555 [money] => 666 [money] => 777 [google] => 888 ) 

Thus, he should randomly select some elements from the 1st array and attach them to all elements in the second.

0
source share
4 answers

As mentioned in all comments, your last array is not possible. What you could do would be something like this:

 finalArray = Array ( [0] => [google] => 111 [1] => [home] => 222 [2] => [google] => 333 ... ) 

You can do it like this (use array_rand for the value of a random array):

 $array3 = array(); foreach ($array2 as $element) { $array3[] = array($element => $array1[array_rand($array1)]); } 
+1
source

As already mentioned, creating such an array is not possible, but you can do something like this:

 $words = array( 'love', 'home', 'google', 'money' ); $numbers = array( 111, 222, 333, 444, 555, 666, 777, 888 ); $result = array(); foreach($words as $word){ $result[$word] = array(); } $wordsmax = count($words) - 1; foreach($numbers as $number){ $result[$words[rand(0,$wordsmax)]][] = $number; } 

This might output something like:

 Array ( [love] => Array ( [0] => 222 [1] => 888 ) [home] => Array ( [0] => 555 [1] => 666 [2] => 777 ) [google] => Array ( [0] => 333 ) [money] => Array ( [0] => 111 [1] => 444 ) ) 
+1
source

Try the following:

 $numbers = Array ( [0] => 111 [1] => 222 [2] => 333 [3] => 444 [4] => 555 [5] => 666 [6] => 777 [7] => 888 ); $text = Array ( [0] => love [1] => home [2] => google [3] => money ); $new_array = array(); foreach($numbers as $value){ $new_array } 

Strike>

I was just about to try this, then I remembered. Array keys must be unique . In other words, cannot have 2 elements in an array with the same key.

0
source

array_combine will use one array for keys and one for values: http://www.php.net/manual/en/function.array-combine.php

 $keys = array ( 'love', 'home', 'google', 'money' ); $vals = array ( 111, 222, 333, 444, 555, 666, 777, 888 ); $output = array_combine($keys, $vals); 

This is no coincidence. Random requires a loop:

 $output = array(); foreach ($keys as $k) { $output[$k] = $vals[array_rand($vals)]; } /* output: Array ( [love] => 666 [home] => 555 [google] => 222 [money] => 777 ) */ 

Codepad: http://codepad.org/7c55LvXg

Another approach using shuffle to mix arrays. This seems to give better results:

 shuffle($keys); shuffle($vals); $output = array(); while (count($keys) > 0 && count($vals) > 0) { $key = array_pop($keys); $output[$key] = array_pop($vals); } /* output: Array ( [love] => 555 [money] => 777 [home] => 444 [google] => 333 ) */ 

Codefall for the latter: http://codepad.org/BpM8RzD3

0
source

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


All Articles