1

I would like to randomize the order of my json objects. Here is the output:

output

And here is my code so far:

// check for empty result
    if (mysql_num_rows($result1) > 0) {
        // looping through all results
        // products node

        while ($row = mysql_fetch_array($result1)) {
            // temp user array
            $feedMain["user_id"]         = $row["user_id"];

            // push single product into final response array
            array_push($response["feedMain"], $feedMain);
        }
        // success
        $response["success"] = 1;

    } 


    // check for empty result
    if (mysql_num_rows($result2) > 0) {
        // looping through all results
        // products node

        while ($row = mysql_fetch_array($result2)) {
            // temp user array
            $feedMain["user_id"]         = $row["user_id"];

            // push single product into final response array
            array_push($response["feedMain"], $feedMain);
        }
        // success
        $response["success"] = 1;

    } 

    // check for empty result
    if (mysql_num_rows($result3) > 0) {
        // looping through all results
        // products node

        while ($row = mysql_fetch_array($result3)) {
            // temp user array
            $feedMain["user_id"]         = $row["user_id"];
            // push single product into final response array
            array_push($response["feedMain"], $feedMain);
        }
        // success
        $response["success"] = 1;

        // echoing JSON response        
        echo json_encode($response, JSON_UNESCAPED_UNICODE);
    }

I tried something like :

echo json_encode(shuffle($response), JSON_UNESCAPED_UNICODE);

and other code snippets but nothing won't work for me.. I just want to randomize the order of the json objects. Thanks.


result1,2 and 3 are mysql statements :)

2
  • 1
    shuffle() returns a boolean, not the shuffled array, so run that call before the json_encode. Also, don't you mean to shuffle $response['feedMain'] rather than $response? Commented Jun 10, 2016 at 13:34
  • 1
    Also use sufffle($response['feedMain']) as I assume you only want to randomize that. Commented Jun 10, 2016 at 13:35

1 Answer 1

1

shuffle will not walk the array deeply. What you should shuffle is $response["feedMain"]:

shuffle($response["feedMain"]);
echo json_encode($response, JSON_UNESCAPED_UNICODE);
Sign up to request clarification or add additional context in comments.

1 Comment

yeah, thanks! I always shuffled the full "$response".. It can be so easy! Thank you so much..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.