SAM SAM - 1 year ago 94
JSON Question

How to shuffle the arrays in for loop manually?

I'v written 2 codes to shuffle some arrays whitch are in a for loop


$numbers = range(0, sizeof($array_id)-1);
foreach ($numbers as $number) {
$arr = array("user" => array("id" => $array_id[$number], "name" => $array_name[$number], "key" => $array_key[$number]));
echo json_encode($arr);

This one has a big problem and that's if the
in one of the arrays equals to 5 it won't loop to put another result of
in the that array, for example the result would be something like this:


All of my arrays have 5 values in them and you can see it returned them defectively.I'll be thankful if anyone can tell me why when
gets the max value in range by shuffle and array gets that
it stocks?


function shuffle_assoc(&$array) {
if (shuffle($array)) {
return $array;
return FALSE;
for ($y=0; $y<sizeof($array_id); $y++) {
$arr = array("user" => array("id" => shuffle_assoc($array_id), "name" => shuffle_assoc($array_name), "key" => shuffle_assoc($array_key)));
echo json_encode($arr);

This one works fine But I want the
to be match I mean they shuffle the same(if $array_id[2] then array_name[2]) that's why I wrote the first code.anyway for this one if anyone knows how to make
shuffle the same I'll be appreciate that.(sorry if I had mistakes in my writing my first language isn't English but I love English :)

Answer Source

I'm not sure that I completely understood you, but

$numbers = range(0, 5);
// $number = array(0, 1, 2, 3, 4, 5)

All of my arrays have 5 values



So you haven't $array_id[5]. I think you need $numbers = range(0, 4);


Once again, I'm not sure if you want this to happen.

$array_id = array(1,2,3,4,5);
$array_name = array('a','b','c','d','e');
$numbers = range(0, 4);
$arr = array();
foreach ($numbers as $number) {
$arr["id"][] = $array_id[$number];
$arr["name"][] = $array_name[$number];
$arr2 = array("user" => array("id" => $arr["id"], "name" => $arr["name"]));
echo json_encode($arr2);

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