SAM SAM - 4 months ago 23
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

First:

$numbers = range(0, sizeof($array_id)-1);
shuffle($numbers);
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
$number
in one of the arrays equals to 5 it won't loop to put another result of
$number
in the that array, for example the result would be something like this:

{"user":{"id":["18","2","36"],"name":["alex","john"],"key":["159","228,"486,"852"]]}}


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
$number
gets the max value in range by shuffle and array gets that
$number
it stocks?





Second:

function shuffle_assoc(&$array) {
if (shuffle($array)) {
return $array;
}else{
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
id
and
name
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
id
and
name
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

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

It's

$array_id[0]
$array_id[1]
$array_id[2]
$array_id[3]
$array_id[4]

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

EDIT:

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

<?php
$array_id = array(1,2,3,4,5);
$array_name = array('a','b','c','d','e');
$numbers = range(0, 4);
shuffle($numbers);
$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);

?>
Comments