One array is
Array (
[0] => love
[1] => home
[2] => google
[3] => money
)
And another is
Array (
[0] => 111
[1] => 222
[2] => 333
[3] => 444
[4] => 555
[5] => 666
[6] => 777
[7] => 888
)
I want to make 3th array that looks like this:
Array (
[love] => 111
[google] => 222
[home] => 333
[love] => 444
[google] => 555
[money] => 666
[money] => 777
[google] => 888
)
So, it should randomly select some of elements from 1st array and join them to all elements in 2nd.
Try this:
$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
}
I was just about to try this then I remembered. Array keys have to be unique -- In other words you cannot have 2 elements in the array with the same key.
array_combine
will use one array for the keys and one for the 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 not random, though. 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 the arrays up. This seems to yield the nicest 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
)
*/
Codepad for the last one: http://codepad.org/BpM8RzD3
Like mentioned in all the comments, your final 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 could achvieve this like this (use array_rand for random array value):
$array3 = array();
foreach ($array2 as $element) {
$array3[] = array($element => $array1[array_rand($array1)]);
}
As mentioned, to create 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 could 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
)
)