Php从json数组中获取随机jsonobjects

时间:2022-05-28 03:36:09

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

我想随机化我的json对象的顺序。这是输出:

Php从json数组中获取随机jsonobjects

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.

和其他代码片段,但没有什么不适合我..我只是想随机化json对象的顺序。谢谢。


result1,2 and 3 are mysql statements :)

result1,2和3是mysql语句:)

1 个解决方案

#1


1  

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

洗牌不会深深地走遍阵列。你应该洗牌的是$ response [“feedMain”]:

shuffle($response["feedMain"]);
echo json_encode($response, JSON_UNESCAPED_UNICODE);

#1


1  

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

洗牌不会深深地走遍阵列。你应该洗牌的是$ response [“feedMain”]:

shuffle($response["feedMain"]);
echo json_encode($response, JSON_UNESCAPED_UNICODE);