0

I have this snippet where I am trying to generate array of array of array of random numbers.

function generateRandomNumbers($pACount, $pBCount, $pCCount, $pDCount) {
    $points = array();
    $score = array();
    $res = array();
    $val = array();
    for ($i = 0; $i <= $pACount; $i++) {
        for ($j = 0; $j <= $pBCount; $i++) {
            for ($k = 0; $k <= $pCCount; $i++) {
                for ($l = 0; $l <= $pDCount; $i++) {
                    $points[] = rand(5, 95);
                }
                $score[] = $points;
            }
            $res[] = $score;
        }
        $val[] = $res;
    }
    return $val;
}

When I return this to AJAX it is returned as: [[[[5, 32, 73, 62, 45]]]] which was suppose to be

[[[[5, 32, 73, 62, 45], [15, 2, 7, 6, 50]],[[25, 52, 93, 2, 5], [16, 32, 67, 63, 15]]]]

I am reletively very new to php coding(started a week back) and I have no clue here. What am I missing?

1

1 Answer 1

5

You are using $i++ in every for loop, while it was supposed to be $j++, $k++ and $l++.

The corrected code

function generateRandomNumbers($pACount, $pBCount, $pCCount, $pDCount) {
    $points = array();
    $score = array();
    $res = array();
    $val = array();
    for ($i = 0; $i <= $pACount; $i++) {
        for ($j = 0; $j <= $pBCount; $j++) {
            for ($k = 0; $k <= $pCCount; $k++) {
                for ($l = 0; $l <= $pDCount; $l++) {
                    $points[] = rand(5, 95);
                }
                $score[] = $points;
            }
            $res[] = $score;
        }
        $val[] = $res;
    }
    return $val;
}
Sign up to request clarification or add additional context in comments.

Comments

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.