Ashwin
Ashwin

Reputation: 1960

push array into an array in php

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?

Upvotes: 0

Views: 108

Answers (1)

iblue
iblue

Reputation: 30434

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;
}

Upvotes: 5

Related Questions