Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to ask something about multidimensional array, I have a table like this

database

This user is referral each other except for "user". I called out the php code like this

function getRefs($array, $parent = 0, $level = 1) {
    global $conn;
    $ref_users = array();
    foreach ($array as $entry) {
        $stmts = $conn->prepare('SELECT u.id,u.username,u.ref_id FROM users u WHERE ref_id = :uid
        ');
        $stmts->bindValue(':uid', $entry['id']);
        $stmts->execute();
        $stmts->setFetchMode(PDO::FETCH_ASSOC);
        $rows = $stmts->fetchAll();
        foreach ($rows as $e) {
                $ref_users[] =  array(
                    "level"=>$level
                );
                $level++;
        }
    }
    return $ref_users;
}

$stmts = $conn->prepare('SELECT u.id,u.fullname,u.username,u.ref_id FROM users u WHERE ref_id = :uid
');
$stmts->bindValue(':uid', $userid);
$stmts->execute();
$stmts->setFetchMode(PDO::FETCH_ASSOC);
$rows = $stmts->fetchAll();
$arr_refs = $arr_user = array();
foreach($rows as $row) {
    $arr_user['id'] = $row['id'];
    $arr_user['fullname'] = $row['fullname'];
    $arr_user['username'] = $row['username'];
    $arr_user['ref_id'] = $row['ref_id'];
    $arr_user['ref_stats'] = getRefs($rows, $row['id']);
    $arr_refs[]=$arr_user;
}

echo '<pre>';
print_r($arr_refs);
echo '</pre>';

The result is like this when I print_r the code

Array
(
    [0] => Array
        (
            [id] => 2
            [fullname] => user2
            [username] => user2
            [ref_id] => 1
            [ref_stats] => Array
                (
                    [1] => Array
                        (
                            [level] => 1
                        )

                )

        )

    [1] => Array
        (
            [id] => 3
            [fullname] => user3
            [username] => user3
            [ref_id] => 1
            [ref_stats] => Array
                (
                    [1] => Array
                        (
                            [level] => 1
                        )

                )

        )

)

The problem is in array "ref_stats" these array should contains 2 level, but the fact it only show 1 level.

The result should be like this.

    [ref_stats] => Array
        (
            [1] => Array
                (
                    [level] => 1
                )
            [2] => Array
                (
                    [level] => 2
                )

        )

Please help me to fix this code. Need your helping hand


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...