Süleyman Kenar Süleyman Kenar - 1 year ago 149
PHP Question

PHP shuffle numerically indexed object array preserve key-value

I have array like this.

A[0]=>name = "John";
A[0]=>lastname = "Blabla";
A[0]=>genre = "Male";
A[1]=>name = "Cheryl";
A[1]=>lastname = "Blabla";
A[1]=>genre = "Female";

I want to shuffle this array with preserving key-value pairs and without mixing every key. So basicly A[0] will be A[1](there are more than only 2 index just example it should be random) with all of child keys values etc.

How can i do this? Thanks

Answer Source

You can loop through the array and then randomly exchange the values in it.


Working example below.

$array[0]['name'] = "John";
$array[0]['lastname'] = "Blabla";
$array[0]['genre'] = "Male";
$array[1]['name'] = "Cheryl";
$array[1]['lastname'] = "Blabla";
$array[1]['genre'] = "Female";
$array[2]['name'] = "Amy";
$array[2]['lastname'] = "Blabla";
$array[2]['genre'] = "Female";
$array[3]['name'] = "Adam";
$array[3]['lastname'] = "Blabla";
$array[3]['genre'] = "Female";
$array[4]['name'] = "Hitan";
$array[4]['lastname'] = "Blabla";
$array[4]['genre'] = "Male";
$array[5]['name'] = "Mary";
$array[5]['lastname'] = "Blabla";
$array[5]['genre'] = "Female";


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download