2 Replies - 267 Views - Last Post: 25 November 2017 - 12:56 PM Rate Topic: -----

#1 pfar54   User is offline

  • D.I.C Regular

Reputation: 0
  • View blog
  • Posts: 473
  • Joined: 30-April 15

How to combine two arrays

Posted 24 November 2017 - 01:24 PM

I am attempting to create a shuffle feature to pair people up for a gift exchange. I created the basic shell of it and am not really sure where to go from here. I am getting the output to shuffle the data, however I am wanting to combine both the array_give and array_receive variables so that it would output something along the line of:

Paul & Becky are giving to Keith & Jackie.

I am unsure how to combine this, though. The array_give variable does not need shuffled, just the array_receive variable does.

Also is there a way to ensure the results do not display as the following?

Paul & Becky are giving to Paul & Becky

Here is my code. Any help would be appreciated.

HTML

<button type="button" id="shuffle">Create Exchange</button>
<div id="name-output"></div>


JS

$('#shuffle').on('click', function() {
        $.ajax({
            url: 'php/name-selection.php',
            type: 'POST',
            success: function(data) {
                $('#name-output').html(data);
            },
            complete:function(){

            },
            error: function(xhr, textStatus, errorThrown) {
                alert(textStatus + '|' + errorThrown);
            }
        });
    })

PHP

$array_give = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
$array_receive = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');

shuffle($array_receive);

foreach( $array_receive as $receiving) {
    echo $receiving . "<br>";
}


Is This A Good Question/Topic? 0
  • +

Replies To: How to combine two arrays

#2 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2559
  • View blog
  • Posts: 10,277
  • Joined: 03-December 12

Re: How to combine two arrays

Posted 24 November 2017 - 04:40 PM

Something like

$array_give = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
$array_receive = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');

foreach($array_give as $r){
    $used = array_rand($array_receive);
    echo $r . " will give to " . $array_receive[$used] . "\n";
    unset($array_receive[$used]);
	
}


You can add a check to ensure they are not giving to themselves as well.

if($r != $array_receive[$used])

Was This Post Helpful? 1
  • +
  • -

#3 pfar54   User is offline

  • D.I.C Regular

Reputation: 0
  • View blog
  • Posts: 473
  • Joined: 30-April 15

Re: How to combine two arrays

Posted 25 November 2017 - 12:56 PM

Thank you! That is perfect.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1